 Coderbyte

# A common coding interview question elisabethgross Updated on ・2 min read

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.split(', ')
const arr2 = strArr.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 :)

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 :)

Posted on by: ### elisabethgross

I am a full stack engineer, passionate about solving complex problems and collaborating with driven teams! I have 4+ years of experience working at small to mid sized startups.

### Discussion I don't usually do JS, but it has became pretty decent in the last few years:

``````function FindIntersection(strArr) {
const [s1, s2] = strArr.map(a => new Set(a.split(", ")));
const intersection = [...s1].filter(x => s2.has(x));
return intersection.length === 0 ? "false": intersection.join(",");
}
``````

But `[...s1].filter(x => s2.has(x))` is still O(n²), isn't it?

• filter() will step through s1 (=outer forEach)
• s2.has() will check against each element in s2 (=inner forEach), probably exiting early

I'm pretty sure there is a O(s1) + O(s2) = O(n) solution.

Membership tests on `Set`s are O(1) not O(n), in other words there is no inner `forEach`.

To clarify: you don't need to iterate over each element in a set for a membership test. They can be implemented as e.g. hash maps. If a key exists, the element is in the set. Hash map lookups are generally O(1).

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.

FWIW `filter` + `has` is also how the MDN docs define intersection.

developer.mozilla.org/en-US/docs/W...

Good answer but you lost the ordering when using sets.

According to the docs sets will be iterated in insertion order. So the solution will propably work, but rely on an implementation detail to do so, which is not ideal.

Nice solution! Love your use of Sets. Very concise and clear.

``````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.

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;
\$arrB = \$numbersAsArrays;
\$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, \$numbersAsArrays);
\$mapB = array_combine(\$numbersAsArrays, \$numbersAsArrays);

\$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).

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

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

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
}
``````

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

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

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

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)

Pro tip!!

``````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(',');

}
``````

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;
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(", ");
}
}
}
}
}
``````

Is there any difference between

``````String::from("")
``````

and

``````"".to_owned()
``````

?

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.

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]
``````

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]
``````

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: 
console.log(FindIntersection('a, 3', 'b, c, 3')) // outputs: 
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]
``````

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: 
console.log(FindIntersection('a, 3', 'b, c, 3')) // outputs: 
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]
``````

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))

``````

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).map(item => item).join(',');
}
``````

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

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"
``````

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

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 )); ```

``````

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

coderbyte.com/results/philipgg:Fin...

I submitted a 0(2n-a) where a is the number of repetitive elements.

The idea is to use that the arrays are sorted so always increment from where we are.

if the elements are matching, save and then increment both counters.

Else increment the count of the array which has the lower number, to try to find the bigger one. (this is auto-switching between the two.)

Nice! Was waiting for someone to come up with this one!

My solution was the same.
When it comes to challenges I prefer algorithms that can be written in pseudocode and don't use many special (or language-specific) data types.

``````import pytest

def findIntersection(arr):
unique = list()
duplicates = []
for string in arr:
for char in string.split(','):
if int("".join(char)) in unique:
duplicates.append(int("".join(char)))
else:
unique.append(int("".join(char)))

return duplicates

@pytest.mark.parametrize(
("arr_s", "expected"),
(["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"], [1, 4, 13]),
)
def test(arr_s, expected):
assert findIntersection(arr_s) == expected

if __name__ == "__main__":
x = ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
print(findIntersection(x))
``````

In JavaScript.

``````function findIntersection(strArr) {
const arr = strArr.join(",").replace(/\s+/g, "").split(",");
const count = {};
const common = [];

arr.map(i => count[i] ? count[i]++ : count[i] = 1);

for (const i in count) {
if (count[i] > 1) {
common.push(parseInt(i, 10));
}
}

return common.length ? common.sort((a, b) => a > b).join(",") : false;
}
``````

This is my O(n) solution. We don't need to parse any of the strings to an integer.

``````
const findIntersection = (arr) => {

// n1 - larger array
// n2 - smaller array

let n1, n2;

if (arr.split(',').length > arr.split(',').length) {
n1 = arr.split(',');
n2 = arr.split(',');
} else {
n1 = arr.split(',');
n2 = arr.split(',');
}

let len = n1.length;

// store the common items
let common = [];

for (let i = 0; i < len; i++) {

// check if an item of one array (larger one) exists in the other array (smaller one)
if (n2.includes(n1[i])) {
common.push(n1[i]);
}

}

return common.length ? common.join() : "false" ;
}

``````

Python solution, not in a nice format, and assuming the input are two integer arrays:

``````
def common_arr(first, second):
mi, ma = (first,second) if len(first) <= len(second) else (second,first)
common = []
i = 0
j = 0
while(i < len(mi)):
if(mi[i] == ma[j]):
common.append(mi[i])
i += 1
if j < len(ma)-1:
j += 1
else:
break
elif mi[i] < ma[j]:
i += 1
else:
if j < len(ma)-1:
j += 1
else:
break

return common

arr = common_arr([1,2,3,4,5,9],[3,5,6,8,9])
print(arr)
``````

So idea:
You iterate over the smallest array, at each step, you are in one of 3 situations

arr1[i] == arra2[j] // you increment i and j because of the invariant, that says the arrays are sorted, so if you found a match you can safely increment.

arr1[i] < arr2[j] // since at index i we have the smallest element, we increment that one because being sorter we ca safely increment until we hit what is at index j or greater

arr1[i] < arr2[j] // same as above only for j

``````function FindIntersection(strArr) {
return
strArr
.map(e => e.split(','))
.reduce((listA, listB) => {
const listFiltered = listA.filter(itemA => listB.includes(itemA));
return listFiltered.length ? listFiltered : false;
});
}
``````

``````use std::cmp::Ordering;

fn main() {
let a = find_intersections([
String::from("-2, -1, 1, 1, 1, 2, 3, 6"),
String::from("-1, 1, 1, 3, 4, 5, 6")
]);
println!("{}", a);
}

fn find_intersections(arr: [String; 2]) -> String {
let mut inter : Vec<isize> = Vec::new();
let mut a = arr.split(",").map(
|e| e.trim().parse::<isize>().unwrap()
);
let mut b = arr.split(",").map(
|e| e.trim().parse::<isize>().unwrap()
);

let mut tmp_a = a.next();
let mut tmp_b = b.next();

while tmp_a.is_some() && tmp_b.is_some() {
match tmp_a.unwrap().partial_cmp(&tmp_b.unwrap()).expect("NAN is evil") {
Ordering::Less => tmp_a = a.next(),
Ordering::Equal => {inter.push(tmp_a.unwrap()); tmp_a = a.next();tmp_b = b.next()},
Ordering::Greater => tmp_b = b.next(),
}
}

if inter.is_empty() {
return String::from("false")
}
return inter.into_iter().map(|x| x.to_string()).collect::<Vec<String>>().join(", ")
}
``````

A rust solution, im quite new to rust, so this is probably quite ugly

A simple and straightforward O(m+n) solution.

``````const FindIntersection = array => {
const commonNumbers = [];

const array1 = array.split(", ").map(num => Number(num));
const array2 = array.split(", ").map(num => Number(num));

let index1 = 0;
let index2 = 0;

while (index1 < array1.length && index2 < array2.length) {
if (array1[index1] < array2[index2]) {
index1 += 1;
} else if (array2[index2] < array1[index1]) {
index2 += 1;
} else {
commonNumbers.push(array1[index1]);
index1 += 1;
index2 += 1;
}
}

return commonNumbers.join(", ");
};
``````

EDIT: I just checked the next article and it has the same solution listed. Sorry I did not check that before posting this here.

// I believe key here is that both arrays are sorted
function FindIntersection (strArr) {
const inBothStrings = []
const arr1 = strArr.split(', ')
const arr2 = strArr.split(', ')

let i=0,j=0;
while (i<arr1.length&&j<arr2.length){

//casting to numbers
let a = arr1[i]|0;
let b = arr2[j]|0;

if(a==b){
inBothStrings.push(a)
i++;
j++;
}
else if(a>b){

j++;
}
else if(b>a){
i++;
}

}

return inBothStrings.join(',')
}

Bingo! Nice work!

``````def sortedIntersection([a,b]):
return any([map(set,a.split(', ')).intersection(b.split(', '))])
``````

Would be the easiest to implement (I'm on my phone so I can't check it, also, python)

Thank you!

``````const FindIntersection = arr => {
return arr.match(/\d+/g).filter(v => (
arr.match(/\d+/g).includes(v)
)).join`,` || false
}
``````

Kotlin (any number of strings): pl.kotl.in/Lgfcz5KnV?theme=darcula

I dont understand why anyone would ask you this in an interview ? A massive red flag for me.

Clarification question: can the lists have duplicate values?

Good question! Nope, the lists will not have duplicates in themselves.  