Created
October 1, 2017 08:26
-
-
Save tkssharma/9ace4cce422f4e76af64022bdb251626 to your computer and use it in GitHub Desktop.
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
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