Spot the bug - #60

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 flipped. Right now you return false when you find a duplicate, and true only when you don’t find any—so hasDuplicate([2, 7, 4, 7]) prints false even though it clearly has one. The fix is just swapping the 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: the loop is correctly detecting “we’ve seen this before, ” but the function’s contract (“has duplicate? ”) needs to treat that condition as success, not failure. I found a related kirupa. com article that can help you go deeper into this topic.