Sliding Window — The Complete Guide
Master the Sliding Window pattern from first principles. Learn to recognize it instantly, evolve brute-force into optimal solutions, and confidently solve interview questions.
Intuition from Scratch
Why does this pattern exist?
Imagine you're looking at a long row of houses from a train window. The window shows you a few houses at a time. As the train moves, old houses slide out of view on the left and new ones slide in on the right. You never need to look at the entire row at once — just the current window.
That's exactly what the Sliding Window pattern does with arrays and strings. Instead of checking every possible subarray (O(n²) or worse), you maintain a "window" that slides across the data. You add one element on the right, remove one on the left, and update your answer — all in O(1) per step. The total work becomes O(n).
The pattern exists because many problems ask about contiguous subarrays or substrings with some constraint. The brute-force approach checks every start/end pair, but the sliding window exploits the fact that consecutive windows overlap — most of the data is the same, so you only need to process the change.
Analogies to Build Intuition
The Train Window
You're on a train looking through a fixed-size window. As the train moves, you see new scenery on one side and lose it on the other. You never need to look at the entire landscape — just what's in the window right now. That's a fixed-size sliding window.
The Magnifying Glass
Imagine sliding a magnifying glass across a line of text. You can stretch or shrink the glass to find the smallest section that contains all the letters you need. That's a variable-size sliding window — expand until you satisfy the condition, then shrink to optimize.
The Moving Average
Stock charts show a 'moving average' — the average price over the last k days. Each day, you add the new price and drop the oldest one. You don't recalculate from scratch every day. That's the core efficiency of sliding window.
What kind of problems does it solve?
Sliding Window is your go-to when:
- You need the maximum/minimum sum of k consecutive elements
- You need the longest/shortest substring satisfying a condition
- You need to count subarrays with a specific property
- The input is linear (array or string) and the answer involves a contiguous range
- You want to reduce O(n²) brute force to O(n)
The core insight
Sliding Window works because consecutive windows share most of their elements. When you slide the window one step right, you only need to process the one element entering and the one element leaving — not the entire window. This turns O(n × k) into O(n).