Skip to content

Instantly share code, notes, and snippets.

@garryyao
Last active September 3, 2019 10:54
Show Gist options
  • Save garryyao/7ef23a7bcefe7443c8f2ca339d1e987e to your computer and use it in GitHub Desktop.
Save garryyao/7ef23a7bcefe7443c8f2ca339d1e987e to your computer and use it in GitHub Desktop.
find common names - design for performance
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