Drill

ProblemsJavaScript › data

The first repeat

mediumdataJavaScript

A stream of ids is meant to be unique; the audit flags the first value that turns up twice.

firstRepeating(values: list<int>) → int

Solve it in the editor →

Where you start

function firstRepeating(values) {
  
}

Worked examples

CallResult
firstRepeating([2,1,3,1])1
firstRepeating([1,2,3])-1
firstRepeating([4,4])4
firstRepeating([7,7,7])7

Hint

A set of everything so far; the moment you add one that is already there, that is the answer.

Reference solution in JavaScript
function firstRepeating(values) {
  const seen = new Set();
  for (const v of values) {
    if (seen.has(v)) return v;
    seen.add(v);
  }
  return -1;
}

The same problem in another language

More data problems in JavaScript