DEV Community

Cover image for A common coding interview question
elisabethgross for Coderbyte

Posted on • Edited on

A common coding interview question

Hey everyone! Welcome back to Code Review, a series of interview challenges released weekly that are completely free for the community. This week we’ll be working on a common, relatively straightforward question that I personally have been asked multiple times in interviews. I chose this challenge because there are multiple ways to approach the problem, each with various time and space trade-offs.

The Challenge:

Write a function, FindIntersection, that reads an array of strings which will contain two elements: the first element will represent a list of comma-separated numbers sorted in ascending order, the second element will represent a second list of comma-separated numbers (also sorted). Your goal is to return a string of numbers that occur in both elements of the input array in sorted order. If there is no intersection, return the string "false".

For example: if the input array is ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"] the output string should be "1, 4, 13" because those numbers appear in both strings. The array given will not be empty, and each string inside the array will be of numbers sorted in ascending order and may contain negative numbers.

The Brute Force Solution:

A brute-force solution is to loop over the numbers of the first string, and for each number in the first string, loop over all numbers of the other string, looking for a match. If a match is found, concat that value to a result string.

function FindIntersection (strArr) {
  const inBothStrings = []
  const arr1 = strArr[0].split(', ')
  const arr2 = strArr[1].split(', ')
  arr1.forEach(elementArr1 => {
    const numArr1 = parseInt(elementArr1)
    arr2.forEach(elementArr2 => {
      const numArr2 = parseInt(elementArr2)
      if (numArr1 === numArr2) {
        inBothStrings.push(numArr1)
      }
    })
  })
  return inBothStrings.join(',')
}

Although this will work, it is not the most optimal solution. The worst case scenario (if there are no matches) is that for every element in the first string, we will have to iterate through every element in the second string. This has a time complexity of O(nm) where n and m are the size of the given strings.

If you haven’t heard of Big O notation, check out this great article which goes into all the details. Understanding Big O notation and being able to communicate how optimal your solution is to an interviewer is an extremely important part of any technical interview.

Try it Out:

Head on over to Coderbyte and try and solve the problem in a more optimized way. Remember to come back next week where I’ll discuss some other solutions and common pitfalls to this problem. Good luck coding :)

Our newsletter 📫

We’re going to be sending out a small, feature reveal snippet every time we release something big, so our community is the first to know when we break out something new. Give us your email here and we'll add you to our "first to know" list :)

Top comments (48)

Collapse
 
dwilmer profile image
Daan Wilmer
function findIntersection($numbersAsStrings) {
    // parse the strings into numbers
    $numbersAsArrays = array_map(function($string) {
        return explode(', ', $string);
    }, $numbersAsStrings);

    // find the intersections
    $intersection = array_intersect(...$numbersAsArrays);

    // if empty, return string "false"; otherwise, return the numbers as a string
    if (empty($intersection)) {
        return 'false';
    } else {
        return implode(', ', $intersection);
    }
}

because I'd argue that letting your language work for you, and therefore optimizing developer time, is better than optimizing execution time when not strictly necessary.

Collapse
 
dwilmer profile image
Daan Wilmer

To follow up: I made three versions of this code. The first version is as above, the second version has the naive approach to finding the intersection:

// find the intersections
$arrA = $numbersAsArrays[0];
$arrB = $numbersAsArrays[1];
$intersection = [];
foreach ($arrA as $num) {
    if (in_array($num, $arrB)) {
        $intersection[] = $num;
    }
}

and a third approach uses a map for lookup:

// find the intersections
$mapA = array_combine($numbersAsArrays[0], $numbersAsArrays[0]);
$mapB = array_combine($numbersAsArrays[1], $numbersAsArrays[1]);

$intersection = [];
foreach ($mapA as $num) {
    if (isset($mapB[$num])) {
        $intersection[] = $num;
    }
}

Performing some timed tests shows that using the built-in function consistently takes about two to three times as long as the self-built map-based function, growing at roughly O(n) using a random array of size 1000 and 10000. Only in exceptional cases would I not use the built-in function.
The naive approach, on the other hand, grows with O(n²) and takes significantly longer at larger array sizes. However, with 26ms with an array size of 1000, it depends on the use case whether I would start optimizing this (if this isn't easily replaced with a built-in function).

Collapse
 
elisabethgross profile image
elisabethgross

Nice work!! Always always interesting to test out a language's built in methods and know whats what when it comes to time complexity.

Collapse
 
elisabethgross profile image
elisabethgross

When the language solves the problem for you... touché

Collapse
 
devtronic profile image
Julian Finkler
function FindIntersection(strArr) { 

  const allNumbers = strArr.reduce((c, a) => c = [...c, ...a.split(',').map(n => Number(n.trim()))], []);
  const numberCounts = {};
  const duplicates = [];
  allNumbers.forEach((n) => {
    if(!numberCounts.hasOwnProperty(n)){
      numberCounts[n] = 0;
    }
    if(++numberCounts[n] == strArr.length){
      duplicates.push(n);
    }
  })

  return duplicates.join(','); 

}
Collapse
 
firee80 profile image
Firee80

Hi! I wrote a solution that should be able to handle n-number of lines.
Also it does not care if there are duplicate numbers or they are out of order.
It just uses .map and .reduce.. probably it still could be optimized by using Set.

const lines = ['1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8']

const mapArrayToHashTable = items => {
  return items.reduce((last, item) => ({...last, [''+item]: item}), {}) 
}

const getHashTable = line => {
  const textNumbers = line.split(',')
  const numbers = textNumbers.map(number => parseInt(number))
  return mapArrayToHashTable(numbers)
}

const [firstTable, ...otherTables] = lines.map(getHashTable)

const result = otherTables.reduce((last, table) => {
  const keyObjs = Object.keys(table).map(key => last[key] ? {[key]: last[key]} : {})
  return keyObjs.reduce((last, keyObj) => ({...last, ...keyObj}), {})
}, firstTable)

console.log(Object.values(result)) // returns [2,4,6]
Collapse
 
firee80 profile image
Firee80

simplified the solution by using Sets and corrected the answer to correspond the assignment

const lines = ['1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8']

function FindIntersection(lines) {
  const getSet = line => new Set(line.split(',').map(number => parseInt(number)))
  const [firstSet, ...otherSets] = lines.map(getSet)
  const result = [...otherSets.reduce((lastSet, set) => new Set([...set].filter(number => lastSet.has(number))), firstSet)]
  return result.length > 0 ? result : 'false'
}

console.log(FindIntersection(lines)) // outputs: [2,4,6]
Collapse
 
firee80 profile image
Firee80

couldn't help myself.. improved the performance by sorting sets and checking result set. Changed the api from array input to n-amount of params. Also input is filtered from not a number

function FindIntersection(...lines) {  
  const getSet = (line = '') => {
    const numbers = line.split(',').map(number => parseInt(number))
    return new Set(numbers.filter(number => !isNaN(number)))
  }
  const sets = lines.map(getSet)
  const [shortestSet, ...otherSets] = [...sets].sort((setA, setB) => setA.size - setB.size)
  const defaultSet = lines.length > 1 ? shortestSet : new Set([])
  const resultSet = otherSets.reduce((resultSet, set) => {
    const commonNumbers = [...resultSet].filter(number => set.has(number))
    return new Set(commonNumbers)
  }, defaultSet)
  const result = [...resultSet]
  return result.length > 0 ? result : 'false'
}

console.log(FindIntersection()) // outputs: false
console.log(FindIntersection('1')) // outputs: false
console.log(FindIntersection('2', '3')) // outputs: false
console.log(FindIntersection('-1, 0', '0')) // outputs: [0]
console.log(FindIntersection('a, 3', 'b, c, 3')) // outputs: [3]
console.log(FindIntersection('-2, 3', '-4, -2')) // outputs: [-2]
console.log(FindIntersection('1,2,3,4', '2,3,4,5', '3,4,5,6')) // outputs: [3, 4]
console.log(FindIntersection('1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8')) // outputs: [2, 4, 6]
console.log(FindIntersection(...['1, 3, 4, 7, 13', '1, 2, 4, 13, 15'])) // outputs: [1, 4, 13]
Thread Thread
 
firee80 profile image
Firee80

Decided to have a one more improvement for performance (when one Set has size = 0, so no need to reduce other Sets. Also result from reduce is directly an array of numbers).
Also my apologies to @elisabethgross as I noticed the tag #codenewbie in the challenge and my answer isn't really for newbies.

function FindIntersection(...lines) {  
  const getSet = (line = '') => {
    const numbers = line.split(',').map(number => parseInt(number))
    return new Set(numbers.filter(number => !isNaN(number)))
  }
  const sets = lines.map(getSet)
  const [shortestSet, ...otherSets] = [...sets].sort((setA, setB) => setA.size - setB.size)
  const setsToReduce = shortestSet && shortestSet.size > 0 ? otherSets : [] 
  const defaultCommonNumbers = lines.length > 1 ? [...shortestSet] : []
  const resultCommonNumbers = setsToReduce.reduce((commonNumbers, set) => 
    commonNumbers.filter(number => set.has(number)), defaultCommonNumbers)
  return resultCommonNumbers.length > 0 ? resultCommonNumbers : 'false'
}

console.log(FindIntersection()) // outputs: false
console.log(FindIntersection('1')) // outputs: false
console.log(FindIntersection('2', '3')) // outputs: false
console.log(FindIntersection('-1, 0', '0')) // outputs: [0]
console.log(FindIntersection('a, 3', 'b, c, 3')) // outputs: [3]
console.log(FindIntersection('-2, 3', '-4, -2')) // outputs: [-2]
console.log(FindIntersection('1,2,3,4', '2,3,4,5', '3,4,5,6')) // outputs: [3, 4]
console.log(FindIntersection('1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8')) // outputs: [2, 4, 6]
console.log(FindIntersection(...['1, 3, 4, 7, 13', '1, 2, 4, 13, 15'])) // outputs: [1, 4, 13]
Collapse
 
idanarye profile image
Idan Arye

Rust solution - works for any number of strings:

fn find_intersection(strings: &[&str]) -> String {
    if strings.is_empty() {
        // NOTE: mathematically speaking, the result here should be **all** the numbers - but we
        // obviously can't return that...
        return "".to_owned(); // no arrays to intersect
    }
    let mut iterators: Vec<_> = strings.iter().map(
        |s| s.split(',').map(|n| n.trim().parse::<isize>().unwrap())
    ).collect();
    let mut current_values = Vec::with_capacity(iterators.len());
    for it in iterators.iter_mut() {
        if let Some(value) = it.next() {
            current_values.push(value);
        } else {
            return "".to_owned(); // at least one array is empty => intersection is empty
        }
    }
    let mut result = Vec::<String>::new();

    loop {
        let (min_value, min_count) = {
            let mut min_value = current_values[0];
            let mut min_count = 1;
            for value in current_values.iter().skip(1) {
                use std::cmp::Ordering::*;
                match value.cmp(&min_value) {
                    Less => {
                        min_value = *value;
                        min_count = 1;
                    },
                    Equal => {
                        min_count += 1;
                    },
                    Greater => {},
                }
            };
            (min_value, min_count)
        };
        if min_count == current_values.len() {
            result.push(min_value.to_string());
        }
        for (current_value, it) in current_values.iter_mut().zip(iterators.iter_mut()) {
            if *current_value == min_value {
                if let Some(value) = it.next() {
                    assert!(*current_value <= value, "numbers must be ordered");
                    *current_value = value;
                } else {
                    return result.join(", ");
                }
            }
        }
    }
}
Collapse
 
gabgab2003 profile image
DownloadPizza

Is there any difference between

String::from("")

and

"".to_owned()

?

Collapse
 
idanarye profile image
Idan Arye

None that I'm aware of. I prefer "".to_owned() over String::from("") or "".to_string() to avoid the confusion of "why are you converting a string to a string?" that I've seen in some newbie Rust threads.

Collapse
 
cxsttlx profile image
Juan Castillo • Edited

this is my solution, Im no pretty good at JS but I want to be a master on it :)

const FindIntersection  = (str) => {
  const arr = str.flatMap(i => i.split(', '))
  const itr = [...new Set(arr.filter((unique, index) => arr.indexOf(unique) !== index))]
  return itr.length ? itr : false
}
Collapse
 
cxsttlx profile image
Juan Castillo

ok, i have no idea to make my code look like editor

Collapse
 
elisabethgross profile image
elisabethgross • Edited

Nice job! And try surrounding your code with triple backticks to format the code ;)

Thread Thread
 
cxsttlx profile image
Juan Castillo

thanks I made it :D i'll wait for more

Thread Thread
 
gabgab2003 profile image
DownloadPizza

also you can put javascript directly after your backticks to make it have syntax highlighting (maybe its js, dont know, also works for other languages)

Thread Thread
 
elisabethgross profile image
elisabethgross

Pro tip!!

Collapse
 
jkodev profile image
Jonathan Jasson Huamani Cuadros

This is my approach.

function intersection(stringArray) {
    const parseArray = (array) => [...new Set(array.split(',').map(item => item.trim()))];
    const [a, b] = stringArray;
    const aParsed = parseArray(a);
    const bParsed = parseArray(b);
    const mergedData = [...aParsed, ...bParsed];
    const counter = {};
    mergedData.forEach(item => {
        counter[item] = (counter[item] || 0) + 1;
    });
    return Object.entries(counter).filter(item => item[1] > 1).map(item => item[0]).join(',');
}
Collapse
 
elisabethgross profile image
elisabethgross

Nice custom parseArray function!! And I like that use of Object.entries().

 
thorstenhirsch profile image
Thorsten Hirsch

Yes, I've looked up how Set works and you're right. Thanks for clarifying.

Another cool solution (but not as readable as yours) however is this "destructive" one on SO.

Collapse
 
artezan profile image
artezan

I used for loop so that improve the performance


const input = ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
function FindIntersection(strArr) {
  const inBothStrings = []
   const [arr1,arr2] = strArr.map(item => item.split(", "))

  for (let index = 0; index < arr1.length; index++) {
    const element1 = arr1[index];
    const indexFound= arr2.findIndex(element2 => element2 === element1)

    if (indexFound !== -1) {
      inBothStrings.push(element1)
      arr2.splice(indexFound, 1)
    }
  }
  return inBothStrings.length ? inBothStrings.join(',') : false 
}
console.log(FindIntersection(input))

Collapse
 
lisabenmore profile image
Lisa Benmore • Edited

fwiw, another js option:

jsfiddle.net/4usxLhyo/1/

sorry, first post, not sure how to get the js syntax highlighting...
Edit: thanks @elisabethgross for the syntax highlighting help!

console.clear()

const one = '1,3,5,5,7,9,9';
const two = '2,4,5,6,8,9,9';
const three = '1,3,5,7,9';
const four = '2,4,6,8';

function findThings (str1, str2) {
  const arr1 = str1.split(',');
  const arr2 = str2.split(',');
  const result = [];

  for (const i of arr1) {
    if (arr2.indexOf(i) > -1) {
      result.push(i);
      arr2.splice(arr2.indexOf(i), 1);
    }
  }

  return result.length ? result : false;
}

console.log(findThings(one, two));
console.log(findThings(three, four )); ```


Collapse
 
elisabethgross profile image
elisabethgross • Edited

Nice! If you use the triple backticks, you can write javascript next to the top triple backticks. Check out this helpful markdown cheat sheet!

Collapse
 
assafsch profile image
Assaf Schwartz • Edited

Not a JS guy, so I decided to do it in Python.
As an interviewer, for these kind of question I'm not a fan of leveraging too much of the language built-ins (such as sets), as it masks algorithmic thinking, which I believe is an important part of the interview.

My solution uses a dictionary to count the number of occurrences for every item.

from collections import defaultdict

def find_intersect(strings):
    a, b = strings
    a = a.split(",")
    b = b.split(",")
    counter = defaultdict(int)
    intersect = list()
    for idx in range(max(len(a), len(b))):
        if idx < len(a):
            item = int(a[idx])
            counter[item]=counter[item]+1
            if counter[item] > 1:
                intersect.append(item)
        if idx < len(b):
            item = int(b[idx])
            counter[item]=counter[item]+1
            if counter[item] > 1:
                intersect.append(item)
    return intersect if intersect else "false"
Collapse
 
elisabethgross profile image
elisabethgross

I agree about not leveraging too many language built-ins, or, making sure to talk about the time complexity of those built-ins!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.