Code Quiz

Find First Duplicate With a Set

A Set-based duplicate finder has an ordering bug that makes it always return the first element.

Codejavascript
function firstDuplicate(nums) {
  const seen = new Set();
  for (const n of nums) {
    seen.add(n);
    if (seen.has(n)) {
      return n;
    }
  }
  return -1;
}

console.log(firstDuplicate([3, 1, 4, 1, 5])); // expected 1

What is the bug that makes this function return the wrong value?