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.
firstRepeating(values: list<int>) → int
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int firstRepeating(std::vector<int> values) {
}
Worked examples
| Call | Result |
|---|---|
firstRepeating(std::vector<int>{2, 1, 3, 1}) | 1 |
firstRepeating(std::vector<int>{1, 2, 3}) | -1 |
firstRepeating(std::vector<int>{4, 4}) | 4 |
firstRepeating(std::vector<int>{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 C++
int firstRepeating(std::vector<int> values) {
std::set<int> seen;
for (int v : values) {
if (seen.find(v) != seen.end()) return v;
seen.insert(v);
}
return -1;
}