Drill

ProblemsC# › data

The first repeat

mediumdataHash mapsArraysC#

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

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.

Solve it in Python →

Where you start

public int FirstRepeating(List<int> values) {
    
}

Worked examples

CallResult
FirstRepeating(new List<int> { 2, 1, 3, 1 })1
FirstRepeating(new List<int> { 1, 2, 3 })-1
FirstRepeating(new List<int> { 4, 4 })4
FirstRepeating(new List<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#
public int FirstRepeating(List<int> values) {
    var seen = new HashSet<int>();
    foreach (var v in values) {
        if (seen.Contains(v)) return v;
        seen.Add(v);
    }
    return -1;
}

The same problem in another language

More data problems in C#