What is the Longest Substring
Return the length of the longest substring whose characters are all different. The right edge walks forward. When a character repeats inside the window, the left edge jumps past the previous copy.
abcabcbb 3
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index is visited by R and at most once by L. |
| Memory | O(1) | The last-index table has one slot per character kind. |
Implementation
def longest_unique(s):
last, l, best = {}, 0, 0
for r, ch in enumerate(s):
if ch in last and last[ch] >= l:
l = last[ch] + 1
last[ch] = r
best = max(best, r - l + 1)
return best