Sliding Window · Variable size

Longest Substring Visualizer

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

Check every substringTrying every pair of ends and scanning the inside is too slow on a long string.
Shrink only when a repeat appearsStore the last index of each character. If that index is still inside the window, move the left edge to the next position.

Interactive solution

The current distinct window, L to R
L = 0
for each R:
if s[R] is already inside the window, move L past it
remember this index of s[R]
best = max(best, R - L + 1)
return best
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each index is visited by R and at most once by L.
MemoryO(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