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
The bug is just the boolean logic vs the function name: you’re returning false when you do find a duplicate, and true when you never find one. So hasDuplicate([2, 7, 4, 7]) prints false even though 7 repeats.
Swap the return values so the “already seen” branch returns true, and the fall-through returns false:
function hasDuplicate(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) return true;
seen.add(n);
}
return false;
}
1 Like