DSA · Arrays · Fixed and variable windows
Slide the window, keep the sum
Two neighbouring windows share almost every element. Let one element in, let one element out, repair the running total — and a whole family of subarray questions drops from O(n·k) to O(n).
Step through both versions on 2 1 5 1 3 →01 The idea
The overlap is the whole trick
A window is a block of consecutive elements — a subarray you treat as one unit. A surprising number of questions are really window questions: the largest sum of any three in a row, the longest stretch that stays under a limit, the longest substring with no repeated letter.
The obvious way is to build every window from scratch. Over 2 1 5 1 3 with a width of 3 that is 3 windows and 9 additions. Now look at what two neighbouring windows share. Indices 0–2 hold 2, 1, 5 and indices 1–3 hold 1, 5, 1. The 1 and the 5 are in both. Adding them again is work you already did.
02 Hand trace
k = 3 over 2 1 5 1 3
Find the largest sum of any three neighbouring numbers in 2 1 5 1 3. Five elements and a width of three give 3 windows. Rose boxes are inside the window right now. Watch the sum, not the elements.
Three windows, but only the first one was added up in full. The other two cost one addition and one subtraction each — 7 arithmetic operations instead of 9. That gap looks small on five numbers, so scale it: on a list of 100 with a width of 50, rebuilding costs 51 windows × 50 = 2550 additions, while sliding costs 50 + 2 × 50 = 150 operations. That is the worst case for the naive version — recomputing hurts most at k = n/2, and eases off again as k approaches n, because there are barely any windows left to build. The code in section 03 is what removes the gap entirely.
03 Naive vs improved
The same answer, two very different costs
Both versions return the largest sum of k consecutive numbers. The left one is what you write first. The right one is the same idea with the inner loop deleted.
Recompute every window
best = -infinityfor start = 0 to n - k: sum = 0 for t = start to start + k - 1: sum = sum + nums[t] best = max(best, sum)return best
Slide the window
sum = 0for t = 0 to k - 1: sum = sum + nums[t]best = sumfor r = k to n - 1: sum = sum + nums[r] - nums[r - k] best = max(best, sum)return best
The inner loop is gone. It was re-adding the k−1 elements the previous window had already counted — the 1 and the 5 you saw shared in the trace. Deleting it is the entire optimisation; everything else is bookkeeping to make the deletion safe.
The first window is paid for by hand. There is nothing to slide from yet, so lines 2–3 spend the full k additions once. Every window after that costs two, no matter how wide k is.
nums[r - k] is the element leaving. When the right edge sits at r, the window covers r-k+1 through r, so the position immediately before it — r-k — is what just fell out. Getting this index wrong by one is the classic sliding-window bug.
When the width is not given
Not every window has a fixed size. Ask instead: how long can the window get while its sum stays at or under a target? The right edge still moves forward every iteration; the left edge only catches up when the rule breaks.
left = 0; sum = 0; best = 0for right = 0 to n - 1: sum = sum + nums[right] # let one in while sum > target: # too big? let some out sum = sum - nums[left] left = left + 1 best = max(best, right - left + 1)return best
Run it on the same list with target 7. Sums go 2, 3, then 8 — too big, so drop the 2 and the window becomes 1–2 with sum 6. Add the next 1 and the window 1–3 sums to exactly 7, width 3. Add the 3 and the sum hits 10, so the left edge drops the 1 and then the 5. The answer is 3, and the winning window is 1 5 1.
The while loop does not make it quadratic. left only ever increases, and every pass of the while body increases it by exactly one — so it can fire at most n times over the whole run, not n times per iteration. Each element enters the window once and leaves at most once: 2n operations, which is O(n).
05 Cheat sheet
The numbers worth carrying into the room
| Case | Cost | Why |
|---|---|---|
| Fixed window, recomputed | O(n · k) | The inner loop re-adds the k−1 elements the last window already counted. Exact cost k(n−k+1), which peaks at k = n/2 — that is where it is genuinely quadratic. |
| Fixed window, slid | O(n) | k additions to build the first window, then exactly 2 operations per slide: k + 2(n−k) = 2n − k in total. |
| Variable window, non-negative values | O(n) | Right edge moves n times, left edge moves at most n times in total. Amortised linear. |
| Extra space, running sum | O(1) | Two indices and one total. The array itself is only read, never copied. |
| Extra space, frequency map | O(k) | Needed when the summary is a character or value count rather than a number. |
| Number of windows of width k | n − k + 1 | 3 windows for n = 5, k = 3. Zero windows when k > n — guard that input. |
06 Where & why
Knowing when the window is the right shape
Sliding window is not a data structure and not a clever trick. It is what you reach for when the answer lives in a contiguous block and that block's summary can be repaired in constant time as the edges move. Everything else is a different pattern wearing a similar name.
Reach for it when…
Use something else when…
| Situation | Better choice | Why |
|---|---|---|
| Best subarray sum, values may be negative | Kadane's algorithm | Shrinking from the left can raise the sum, so the shrink rule breaks. Kadane handles mixed signs in one O(n) pass. |
| Many range-sum queries on a fixed array | Prefix sum array | Build once in O(n), then every range answers in O(1). Re-sliding per query would be O(n) each time. |
| The chosen elements need not be adjacent | Sorting, DP or a heap | A window can only ever look at consecutive positions, so it cannot express "pick any k". |
| You need the maximum inside every window, not the sum | Monotonic deque | A maximum cannot be repaired by subtraction — the leaving element may be the maximum, and nothing tells you the next best. |
07 Interview questions
Eleven answers you should be able to speak
Roughly the order an interviewer escalates: what it is, what it costs, why it costs that, where it breaks, and whether you would really use it.
What is the sliding window technique?
Why is the fixed-size version O(n) and not O(n·k)?
Walk me through max sum of k = 3 on 2 1 5 1 3.
When the right edge is at index r, which index leaves?
Fixed window versus variable window — what actually changes?
The variable version has a while loop inside a for loop. Is that O(n²)?
Why does the technique break with negative numbers?
How much extra space does it need?
Sliding window versus two pointers — are they the same thing?
How many windows of width k are there in an array of length n?
When would you actually use this outside an interview?
08 Practice problems
Six problems, in the order you should attempt them
Every one is solvable with only what this page taught. Work down the list — the last one is where the pattern runs out and something bigger takes over.