Drill

ProblemsPython › text

Longest stretch with no repeat

hardtextPython

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

longest_unique_run(text: string) → int

Solve it in the editor →

Where you start

def longest_unique_run(text: str) -> int:
    

Worked examples

CallResult
longest_unique_run("abcabcbb")3
longest_unique_run("bbbbb")1
longest_unique_run("pwwkew")3
longest_unique_run("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 Python
def longest_unique_run(text: str) -> int:
    last_at = {}
    best = 0
    left = 0
    for i, c in enumerate(text):
        if c in last_at and last_at[c] >= left:
            left = last_at[c] + 1
        last_at[c] = i
        best = max(best, i - left + 1)
    return best

The same problem in another language

More text problems in Python