Skip to content

Instantly share code, notes, and snippets.

@tkssharma
Created October 1, 2017 08:26
Show Gist options
  • Save tkssharma/9ace4cce422f4e76af64022bdb251626 to your computer and use it in GitHub Desktop.
Save tkssharma/9ace4cce422f4e76af64022bdb251626 to your computer and use it in GitHub Desktop.
function intersection(firstArray, secondArray) {
// array1 = [1,5,6,7,8];
// array2 = [3,4,5,7,9];
var hashmap = {};
var intersectionArray = [];
// assign 1 to all index in hashmap
firstArray.forEach(function(element) {
hashmap[element] = 1;
});
// Since we only want to push unique elements in our case... we can implement a counter to keep track of what we already added
// now just check if second array has that index available and should equal to 1
secondArray.forEach(function(element) {
if (hashmap[element] === 1) {
intersectionArray.push(element);
hashmap[element]++;
}
});
return intersectionArray;
// Time complexity O(n), Space complexity O(n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment