Drill

ProblemsC# › text

Longest stretch with no repeat

hardtextSliding windowStringsHash mapsC#

A token generator checks its output for the longest run of characters in which nothing appears twice.

LongestUniqueRun(text: string) → 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 LongestUniqueRun(string text) {
    
}

Worked examples

CallResult
LongestUniqueRun("abcabcbb")3
LongestUniqueRun("bbbbb")1
LongestUniqueRun("pwwkew")3
LongestUniqueRun("abcdef")6

Hint

Slide a window. When a repeat comes in, pull the left edge past where that character was last seen — never backwards.

Reference solution in C#
public int LongestUniqueRun(string text) {
    var lastAt = new Dictionary<char, int>();
    int best = 0, start = 0;
    for (int i = 0; i < text.Length; i++) {
        char c = text[i];
        if (lastAt.ContainsKey(c) && lastAt[c] >= start) start = lastAt[c] + 1;
        lastAt[c] = i;
        best = Math.Max(best, i - start + 1);
    }
    return best;
}

The same problem in another language

More text problems in C#