Last active
September 3, 2019 10:54
-
-
Save garryyao/7ef23a7bcefe7443c8f2ca339d1e987e to your computer and use it in GitHub Desktop.
find common names - design for performance
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
const names = ['Huey', 'Dewey', 'Louie', 'Donald', 'Launchpad']; | |
const moreNames = ['Donald', 'Mickey', 'Minnie', 'Goofy', 'Chip', 'Dale']; | |
/** | |
* Find common names in two arrays of names | |
* @param names1 | |
* @param names2 | |
* @returns {[]} names contained in both arrays | |
*/ | |
const findCommonNames = (names1, names2) => { | |
const shared = []; | |
const dict = new Map(); | |
// O(n) | |
return names1.concat(names2).filter((name) => { | |
if (dict.has(name)) { | |
return true; | |
} else { | |
dict.set(name, 1); | |
return false; | |
} | |
}); | |
} | |
findCommonNames(names, moreNames); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment