Drill

ProblemsC# › network

The first missing sequence number

mediumnetworkArraysSortingC#

A reliable-transport layer assigns monotonically increasing sequence numbers, but packets can arrive out of order or be lost. Find the lowest number starting from zero that has not been seen.

FirstMissingSeq(sequence: 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 FirstMissingSeq(List<int> sequence) {
    
}

Worked examples

CallResult
FirstMissingSeq(new List<int> { 1, 2, 3 })0
FirstMissingSeq(new List<int> { 0, 1, 3 })2
FirstMissingSeq(new List<int> { 0, 1, 2 })3
FirstMissingSeq(new List<int> { })0

Hint

Build a boolean presence array covering 0 through the list length, mark every value that falls in range, then scan for the first gap.

Reference solution in C#
public int FirstMissingSeq(List<int> sequence) {
    int length = sequence.Count;
    bool[] present = new bool[length + 1];
    foreach (int v in sequence) {
        if (v >= 0 && v <= length) present[v] = true;
    }
    for (int i = 0; i <= length; i++) {
        if (!present[i]) return i;
    }
    return length + 1;
}

The same problem in another language

More network problems in C#