Drill

ProblemsJava › data

The first repeat

mediumdataHash mapsArraysJava

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

firstRepeating(values: list<int>) → int

Java 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.

Solve it in Python →

Where you start

int firstRepeating(List<Integer> values) {
    
}

Worked examples

CallResult
firstRepeating(Main.<Integer>ls(2, 1, 3, 1))1
firstRepeating(Main.<Integer>ls(1, 2, 3))-1
firstRepeating(Main.<Integer>ls(4, 4))4
firstRepeating(Main.<Integer>ls(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 Java
int firstRepeating(List<Integer> values) {
    Set<Integer> seen = new HashSet<>();
    for (int v : values) {
        if (seen.contains(v)) return v;
        seen.add(v);
    }
    return -1;
}

The same problem in another language

More data problems in Java