Spot the bug - #51

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

Bug is the return values are backwards for what the name hasDuplicate implies. Right now it returns false the moment it sees a repeat, and true only after it proves there were no repeats.

Flip 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;
}

With [2, 7, 4, 7] this should log true (because 7 shows up twice).

1 Like