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 return values are backwards. Hitting seen.has(n) means you found a duplicate, so that should return true, and the “made it through the loop” case 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;
}
Right now it’s basically saying “duplicate found → false” and “no duplicates → true,” which is the opposite of what the function name implies.
1 Like