Sliding Window
Mindmap
Problem Categories
Anatomy: Expansion, Shrinking, Logic
Every sliding window has the same three phases - Expansion, Shrinking, Logic. What changes between Fixed / Longest / Shortest is which phase uses a while loop (rapid) and which uses a one-line shift (single element), and where the Logic sits.
| Pattern | Expansion | Shrinking | Logic placement |
|---|---|---|---|
| Fixed (size = k) | while until size hits k | one-line (remove 1, left += 1) | between expansion and shrinking - window is always size k here |
| Longest - Sliding | one-line (right += 1) | while invalid (rapid shrink to valid) | after shrink, unconditional maxi = max(maxi, right - left) |
| Longest - Shifting | one-line (right += 1) | one-line if invalid (window slides, never shrinks below peak) | after the if, unconditional maxi = max(maxi, right - left) |
| Shortest | while until valid (rapid grow) | while still valid (rapid shrink) | inside the shrink loop - every valid window updates mini before removing |
Fixed window
Window has a constant size k. Grow to k, do work, slide by one forever.
Longest window - Sliding (full shrink-to-valid)
Window can shrink by many elements when it becomes invalid. Use when the constraint requires exact equality or duplicate purging (e.g. dup removal, exact-sum, vowel-order).
Longest window - Shifting (preferred for max-length-with-inequality)
Window never actually shrinks below its peak - it just slides forward by one when invalid. Works whenever the constraint is ≤ something (k distinct, k flips, k cost). See Shifting Window variant in most longest problems.
Shortest window
Window grows until just barely valid, then shrinks as long as it stays valid - recording the smallest valid size along the way. Both phases are rapid while loops; the Logic lives inside the shrink loop because every step inside it is a valid candidate.
Quick mental model
while= rapid phase (the phase doing the heavy lifting for the goal)- One-line = passive phase (just slides past)
- Logic sits next to the rapid phase that produces valid windows:
- Fixed: after Expansion (Expansion produces the valid size-
kwindow) - Longest: after Shrinking (Shrinking restores validity)
- Shortest: inside Shrinking (each step inside is its own valid candidate)
- Fixed: after Expansion (Expansion produces the valid size-