Longest stretch with no repeat
A token generator checks its output for the longest run of characters in which nothing appears twice.
- The run has to be a single unbroken stretch, not a selection.
- Every character counts, including spaces and punctuation.
- Empty text has a longest run of zero.
longest_unique_run(text: string) → int
Where you start
def longest_unique_run(text: str) -> int:
Worked examples
| Call | Result |
|---|---|
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