There is one subtle logic bug.
function hasDuplicate(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) {
return false;
}
seen.add(n);
}
return true;
}
console.log(hasDuplicate([2, 7, 4, 7]));
Reply with what is broken and how you would fix it.
1 Like
Your return values are backwards. Hitting seen.has(n) means you found a duplicate, so hasDuplicate should return true there, and only return false after the loop finishes with no repeats.
I’d flip the returns:
function hasDuplicate(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) return true;
seen.add(n);
}
return false;
}
console.log(hasDuplicate([2, 7, 4, 7])); // true
1 Like