Learn · DSA · Pattern 3
Sliding Window
When a problem asks about a run of consecutive items — a subarray or substring — you rarely need to re-scan each one. You slide a window across and update as you go.
Before we start
- What a “window” is and how sliding it avoids re-work
- Fixed-size vs variable-size windows
- The trigger words that mean “use a sliding window”
- Why it’s O(n) where brute force is O(n²)
- Solve max-sum-of-k and longest-substring problems
- Compute moving averages / “busiest window” efficiently
- Explain how the window slides, out loud
Why you’re learning it: it’s a top-5 interview pattern and the backbone of anything “over the last N” — moving averages, rate limits, streaks. ⏱️ ~25 min.
The idea
Picture a bus with 3 seats driving down a street of people. Each time it moves one stop, one person steps off the back and one steps on the front — you never recount all three, you just adjust by the two who changed. That “adjust, don’t recount” is the whole trick. Recomputing every window from scratch is O(n²); sliding is O(n).
Watch it work — biggest sum of 3 in a row
Array [2, 1, 5, 1, 3, 2]. The highlighted cells are the window.
First window [2,1,5] = 8. (running max shown as we go)
Slide right: drop 2, add 1 → [1,5,1] = 7. (running max shown as we go)
Slide: drop 1, add 3 → [5,1,3] = 9. New max! (running max shown as we go)
Slide: drop 5, add 2 → [1,3,2] = 6. (running max shown as we go)
Answer: 9. One pass, each element added once and removed once.
Two flavours
The window is always k wide (like above). Add the new, subtract the old, track the best.
The window grows and shrinks to satisfy a rule — e.g. “longest substring with no repeats”: expand the right edge, and pull the left edge in when the rule breaks.
Trigger words
Where you’ll use it — real life
A 7-day average of stock prices or sales is a sliding window over time.
“Max 100 requests in any 60-second window” — the API guard you’d build at Ayris is a sliding window over timestamps.
Busiest hour of traffic, longest run of successful payments — all windows over a sequence.
Longest substring without repeats, smallest window containing all letters — classic variable windows.
Why we practice this
The mechanic is easy; spotting “this is a contiguous-run problem” is the skill. A few reps and the trigger words jump out at you.
Now YOU do the reps
Out loud: “Why does sliding a window turn an O(n²) recompute into O(n)?” Then log it in your Journal.
Next: Binary Search →