Created
November 18, 2019 04:25
-
-
Save kirkdrichardson/b301c8530c4a57108bdd0235e88ef4de to your computer and use it in GitHub Desktop.
Use a Frequency Counter Pattern to Check for Duplicates in Javascript Array
This file contains 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
/** | |
* 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