Skip to content

Instantly share code, notes, and snippets.

@kirkdrichardson
Created November 18, 2019 04:25
Show Gist options
  • Save kirkdrichardson/aab3b84ae9cee720b730bcd06b759d40 to your computer and use it in GitHub Desktop.
Save kirkdrichardson/aab3b84ae9cee720b730bcd06b759d40 to your computer and use it in GitHub Desktop.
Use a Frequency Counter Pattern to Check for Duplicates in Javascript Array
/**
* Implement a function called hasDuplicates which accepts
* a variable number of integer arguments and returns
* true if there are duplicates in the arguments.
*
* Should be solved in O(n) or better.
*
*/
function hasDuplicates(...args) {
const o = {};
for (let num of args) {
if (o[num]) return true;
else o[num] = true;
}
return false;
}
console.log(hasDuplicates(1, 2, 3, 4, 5, 6) === false);
console.log(hasDuplicates(-1, -2, -3, -4, 4, 5, 6) === false);
console.log(hasDuplicates(1, 2, 3, 4, 5, 6, 6) === true);
console.log(hasDuplicates(1, 1, 1, 2, 3, 4, 5, 6) === true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment