Spot the bug - #49

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

hasDuplicate is lying right now — it returns false the moment it sees a repeat, and true only when everything’s unique.

Flip those returns so “found a duplicate” is true and “never found one” is 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
1 Like