Visualize

Pattern visualizer

Grow-and-shrink window

A repeat only forces the window to shrink, never to restart from scratch: when s[r] already lives in the window, evicting from the left until that clash clears is enough, because every character removed along the way would only re-trigger the same clash if it stayed. That's why both edges move forward only — r keeps probing new characters while l creeps right just enough to resolve a duplicate — so the window [l..r] never backtracks and each character is added and removed at most once. Reach for it when the answer is a contiguous run and validity can be checked incrementally, like "no repeated characters". Animated on: Longest substring without repeating characters in "abcabcbb".

Sliding Window

step 1 / 18
a
[0]
b
[1]
c
[2]
a
[3]
b
[4]
c
[5]
b
[6]
b
[7]
line 2

Input "abcabcbb". Window [l..r] may hold each char once; a Set remembers what's inside. Start l=0, best=0.

Pseudocode
1seen = an empty set of the characters in the window
2l = 0, best = 0
3FOR each right edge r from 0 to the end of s:
4 WHILE s[r] is already in seen:
5 remove s[l] from seen
6 move l one step right
7 END WHILE
8 add s[r] to seen
9 best = the larger of best and the window size (r - l + 1)
10END FOR
11RETURN best

← / → step · space play · Home restart

Where to practice Sliding Window