Lesson 7.2 · Sliding Window
Variable Windows: Finding the Longest
Grow the right edge every step; when the window breaks the rule, shrink the left edge until it's valid again. Record the size after fixing.
15 min
Think of it like this
Stretching a measuring tape along a row of books looking for the longest run with no repeated colour. You pull the end forward one book at a time. When a colour repeats, you slide the start forward past the earlier book of that colour, then keep pulling.
1.Grow, then shrink
The right pointer moves every iteration and adds one element. If the window is now invalid (a repeated character, too many distinct values, a sum too large), a while loop moves the left pointer forward, removing elements, until it's valid. Then the window [left, right] is the longest valid window ending at right.
Each element is added once and removed at most once, so even with the inner while, total work is O(n).
s = "abcabcbb"in window(list)
best(vars)
Step 1/5Grow to "abc": all different. Length 3.
Remember
- Right moves every step; left moves only to restore validity.
- Measure the window after shrinking.
- Total O(n): each element enters and leaves once.
Common mistakes
- Using
ifinstead ofwhileto shrink (one step may not be enough). - Measuring before fixing the window.