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 logic is backwards — you bail out with false right when you do find a duplicate, and then return true only when you never hit one.
Flip those two returns:
function hasDuplicate(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) return true; // found a dup
seen.add(n);
}
return false; // no dups
}
1 Like