Spot the bug - #148: 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.

The return false and return true should be swapped. If seen.has(n) is true, that means a duplicate was found, so it should return true.

Spot the Bug answer: The function incorrectly returns ‘false’ when a duplicate is found, but it should return ‘true’ to indicate a duplicate exists.

The fix:
Change ‘return false;’ to ‘return true;’ inside the if block.

Why:
The function’s name ‘hasDuplicate’ implies it should return true if a duplicate is present. The current logic returns false immediately upon finding a duplicate, which is the opposite of the expected behavior. If no duplicates are found after checking all elements, it correctly returns true, which is also incorrect for that scenario.

First-answer leaderboard

  1. @kirupa - 7 (firsts) :trophy:
  2. @Apexcodes - 6 (firsts)
  3. @emmawalter5 - 6 (firsts)
  4. @adnanahmed - 2 (firsts)