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 :)
Latest comments (48)
A simple and straightforward O(m+n) solution.
EDIT: I just checked the next article and it has the same solution listed. Sorry I did not check that before posting this here.
In JavaScript.
This is my O(n) solution. We don't need to parse any of the strings to an integer.
I dont understand why anyone would ask you this in an interview ? A massive red flag for me.
Kotlin (any number of strings): pl.kotl.in/Lgfcz5KnV?theme=darcula
A rust solution, im quite new to rust, so this is probably quite ugly
Python solution, not in a nice format, and assuming the input are two integer arrays:
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
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.
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!
Nice! If you use the triple backticks, you can write
javascript
next to the top triple backticks. Check out this helpful markdown cheat sheet!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.
simplified the solution by using Sets and corrected the answer to correspond the assignment
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
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.
Would be the easiest to implement (I'm on my phone so I can't check it, also, python)
// I believe key here is that both arrays are sorted
function FindIntersection (strArr) {
const inBothStrings = []
const arr1 = strArr[0].split(', ')
const arr2 = strArr[1].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!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.