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.
Your return values are flipped. Right now, when you find a duplicate (seen. has(n)), you return false, and when you finish the loop with no duplicates you return true—so hasDuplicate([2, 7, 4, 7]) incorrectly prints false. The fix is just to swap those booleans:
function hasDuplicate(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) return true;
seen.add(n);
}
return false;
}
Mechanism-wise, Set is doing O(1)-ish membership checks, so the whole point is “bail out early” the moment you see a repeat—your code bails out early, just with the wrong answer.