Spot the bug - #95: Duplicate Finder Helper

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.

You’ve got the return values flipped. Hitting seen.has(n) means you found a duplicate, so that should return true. Finishing the loop means you never found one, so 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

The logic is reversed. If a duplicate is found, the function should return true, not false. If the loop finishes without finding any duplicates, 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;
}
1 Like

Yeah that’s it, the return values are just swapped. Finding a dupe should short-circuit to true, and only return false once the whole loop clears without a hit.

1 Like

Spot the Bug answer: The return values are inverted: it returns false when a duplicate is found and true when no duplicates exist, which is backwards.

The fix:

Swap the return values: return true when seen.has(n) is true, and return false after the loop ends.

Why:
The function name implies it should return true if a duplicate is found, but the current logic returns false on finding one and true only if the loop completes without duplicates, which is the opposite of the intended behavior.


Got it: @emmawalter5 :trophy: