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.
The return values are reversed. The function returns false when it finds a duplicate and true when there are no duplicates. Fix it by returning true inside the seen.has(n) condition and false at the end. For [2, 7, 4, 7], it should return true.
The return values are reversed. When a number is already in the Set, the function should return true, and if the loop finishes without finding a duplicate, it should return false.
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
This keeps the same efficient O(n) time complexity while giving the correct result.
Spot the Bug answer: The function returns ‘false’ when a duplicate is found, but it should return ‘true’.
The fix:
Change ‘return false;’ to ‘return true;’ inside the if block.
Why:
The function ‘hasDuplicate’ is intended to check if any element appears more than once. If ‘seen.has(n)’ is true, it means ‘n’ is a duplicate, so the function should immediately indicate that a duplicate exists by returning ‘true’. If the loop completes without finding any duplicates, then ‘false’ should be returned.
Nice catch, @emmawalter5 — the reversed returns are exactly it, and I liked that you didn’t just name the bug, you gave the fix in plain terms too.
The [2, 7, 4, 7] example is a good check for it. With the current code that comes back false even though 7 shows up twice, which is the kind of result that would quietly break anything relying on it. Swapping the two returns, like you said, fixes it without touching the Set logic at all.