The first repeat
A stream of ids is meant to be unique; the audit flags the first value that turns up twice.
- Scan left to right and stop at the first value that has appeared earlier.
- A value repeated later does not matter if a smaller repeat came first.
- No value repeats at all gives -1.
first_repeating(values: list<int>) → int
Where you start
def first_repeating(values: list[int]) -> int:
Worked examples
| Call | Result |
|---|---|
first_repeating([2, 1, 3, 1]) | 1 |
first_repeating([1, 2, 3]) | -1 |
first_repeating([4, 4]) | 4 |
first_repeating([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 Python
def first_repeating(values: list[int]) -> int:
seen = set()
for v in values:
if v in seen:
return v
seen.add(v)
return -1