Created
April 1, 2020 09:45
-
-
Save ronapelbaum/8d255f0499331b2b012c8df06700ed92 to your computer and use it in GitHub Desktop.
javascript interview question - findIntersection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* https://dev.to/coderbyte/a-common-coding-interview-question-461f | |
* https://jsfiddle.net/ronapelbaum/yLkbg4v1/ | |
*/ | |
function sol1(arr1, arr2) { | |
// O(n*m) | |
return arr1.filter(d => arr2.includes(d)); | |
} | |
function sol2(arr1, arr2) { | |
// O(n+m) | |
const res = []; | |
let pop1 = arr1.shift(); | |
let pop2 = arr2.shift(); | |
while (pop1 && pop2) { | |
if (pop1 === pop2) { | |
res.push(pop1); | |
pop1 = arr1.shift(); | |
pop2 = arr2.shift(); | |
} else if (pop1 > pop2) { | |
pop2 = arr2.shift(); | |
} else if (pop2 > pop1) { | |
pop1 = arr1.shift(); | |
} | |
} | |
return res; | |
} | |
function findIntersection(arr, solFunc) { | |
const arr1 = arr[0].split(',').map(d => parseInt(d)); | |
const arr2 = arr[1].split(',').map(d => parseInt(d)); | |
const res = solFunc(arr1, arr2); | |
return res.join(','); | |
} | |
// ======================================= | |
// should be "4, 13" | |
const input = ["3, 4, 7, 13", "1, 2, 4, 5, 6, 13, 15"]; | |
console.log('findIntersection sol1', findIntersection(input, sol1)); | |
console.log('findIntersection sol2', findIntersection(input, sol2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment