Sliding Window Cheat Sheet
Grow a window over a list or string and shrink it from the other side, so a contiguous-range problem finishes in one pass instead of recomputing sums.

Earn the full sheet below.
When to reach for it
- Need the longest or shortest contiguous run.
- Update the running sum, don't recompute it.
- Fixed size, or it grows and shrinks to fit.
- 'At most k' is this pattern winking at you.
What's on the sheet
The steps hold for every problem here. Step 3 changes, and so can what the window tracks: a sum, a count, or a dict.
- Set Up. Two pointers and a running total start here.
- Grow the Window. Expands until the window's cost is big enough.
- Check and record. Your problem defines valid; the window just keeps the books.
- Shrink and Return. Contract left each pass, or it's O(n^2).
Watch out
- Expanding and contracting are separate steps; skip the contraction and you're back to an O(n^2) scan.
- Check b < len(nums) every time you grow the window, or you'll index past the end.
- The window's 'cost' isn't always a sum. Fruit into Baskets tracks distinct-element counts in a dict instead.
How to earn it
Solve half of the Sliding Window problems on InterviewCrunch and the sheet is yours. Free accounts included. Members can download every sheet right away.
Want to see a finished sheet first? Preview the Two Pointers sample.
Every pattern has a sheet. See the full set.