The sliding window template: grow, then shrink
1 Checking every stretch is too slow
We have an array of positive values and a limit. We want the longest window: a stretch of values next to each other whose total is at most the limit. Here the limit is 6:
The answer is 4, the window [1, 1, 3, 1] from index 1 to 4.
The first code most of us write tries every start, and from each start it adds values until the total goes over 6. That is about n²/2 windows. At n = 10⁵ it is around 5 × 10⁹ steps. At about 10⁸ steps a second, that is far past the time limit, so it gets Time Limit Exceeded (TLE).
The two loops repeat work. From start 0, the inner loop adds 2, 1 and 1, and stops at the 3. From start 1, it adds 1, 1 and 3 all over again, though only the 2 has left.
So we keep one window and move its two ends, l on the left and r on the right. Both only ever move to the right. We start with the easier case, a window whose size never changes.
2 A window of fixed size
Some problems fix the size of the window. Here we want the total of every window of 3 values. When the window slides one place, the value on the right comes in and the value on the left goes out. The values in between stay. So the new total is the old total, plus one value, minus one value.
In a loop, r visits every index once. The value that leaves is k places behind it:
total = 0
for r from 0 to n − 1:
total += nums[r] // nums[r] comes in
if r >= k:
total -= nums[r − k] // nums[r − k] goes out
if r >= k − 1:
record total // the window r − k + 1 to r
Adding up every window from scratch costs k steps per window, about n × k in all. At n = 10⁵ and k = 5 × 10⁴, that is around 5 × 10⁹ steps, and TLE. Sliding costs two steps per window, so the whole pass is O(n). The same trick works for any state that can take one value in and let one value out, such as counts of letters.
3 Grow, then shrink
In our problem the size is not fixed. The window stretches while it can and gives up values when it must. A window is valid when it follows the rule, here a total of at most 6. Otherwise it is broken.
Each step of the loop does three things, in this order:
- Grow.
rmoves one place right.nums[r]enters, and we add it tototal. - Shrink. While the window is broken,
nums[l]leaves. We subtract it, andlmoves right. - Record. The window is valid again. If it is longer than
best, it becomes the newbest.
Blue is a valid window, orange is a broken one, and a crossed box has left for good:
The same run as a table, with the total before and after the shrink:
| r | enters | total | leaves | l | best |
|---|---|---|---|---|---|
| 0 | 2 | 2 | 0 | 1 | |
| 1 | 1 | 3 | 0 | 2 | |
| 2 | 1 | 4 | 0 | 3 | |
| 3 | 3 | 7 → 5 | 2 | 1 | 3 |
| 4 | 1 | 6 | 1 | 4 | |
| 5 | 3 | 9 → 4 | 1, 1, 3 | 4 | 4 |
At r = 5, the shrink ran three times in one step. After the first 1 left, the total was 8, still broken. So the shrink is a while, not an if.
4 Why l never moves back
The loop never tries a start before l again, so it never checks windows such as index 0 to 4. To see why it can skip them, we write every window in a grid, like the grid of pairs in the two-pointers lesson. The row is the start l, the column is the end r, and each cell holds that window's total. The orange row and column hold the indexes.
The crossed cells fill the top-right corner, with an edge like a staircase. The values are positive, so a window that grows only gets a bigger total:
- Right of a crossed cell, the window has the same start and a later end. It holds the crossed window, so it is over 6 too.
- Above a crossed cell, the window starts earlier and ends in the same place. It holds the crossed window too.
So a broken window stays broken as it grows. In each column, the valid windows form one run down to the diagonal. The shrink stops at the top of that run, so the window is the longest valid one that ends at r. In the next column, the run starts at the same row or lower, so l never has to move back. Every window the loop skips is crossed, or shorter than one it recorded.
5 The code and the cost
The code follows the three steps. best starts at 0, for an array where every value alone is over the limit.
C++
total is a long long. 10⁵ values of 10⁹ add up to 10¹⁴, far more than an int holds.
total is a long. 10⁵ values of 10⁹ add up to 10¹⁴, far more than an int holds.
Nothing to watch. Python's integers grow as needed.
Nothing to watch. Numbers stay exact up to about 9 × 10¹⁵, so a total of 10¹⁴ is safe.
int is 64 bits on today's machines, so a total of 10¹⁴ fits.
Write r + 1 - l, not r - l + 1. When one value alone is over the limit, the window ends up empty with l = r + 1, and r - l on a usize underflows. The total is an i64, because 10⁵ values of 10⁹ reach 10¹⁴.
total is a long. 10⁵ values of 10⁹ add up to 10¹⁴, far more than an int holds.
On our array, every tab returns 4 for limit 6, 2 for limit 2 and 0 for limit 0.
The while inside the for looks like O(n²), but it is not. r moves n times. l only moves forward, so it moves at most n times in the whole run, not n times per step. That is at most 2n moves, the right and down steps of the walk on the grid. So the time is O(n): at n = 10⁵, around 2 × 10⁵ steps instead of 5 × 10⁹. The window keeps a total and two indexes, so the extra space is O(1).
6 The shortest window: one line moves
Now we ask the opposite question on the same array: the shortest window with a total of at least 7. Those windows are exactly the crossed cells. The longest question wanted the uncrossed cell furthest from the diagonal. This one wants the crossed cell nearest to it:
A total of at least 7 is the same as a total over 6, so the window makes the same moves. The window is good when its total is at least 7. Only the line that records the answer moves:
longest valid window
for r from 0 to n − 1:
add nums[r]
while the window is broken:
remove nums[l], and move l right
best = max(best, r − l + 1)
shortest good window
for r from 0 to n − 1:
add nums[r]
while the window is good:
best = min(best, r − l + 1)
remove nums[l], and move l right
For the longest, we record after the shrink, when the window is valid again. For the shortest, we record inside the shrink, before each value leaves, because the good windows exist only there. At r = 5, the shrink records three of them:
The best of 4 came from r = 3, the window [2, 1, 1, 3]. The answer [3, 1, 3] is good only in step 3. After the shrink, the window is [1, 3] with total 4, so a record there would never see it.
best starts at n + 1, longer than any window. If it is still n + 1 at the end, no window reached the target, and the answer is 0.
On our array, every tab returns 3 for target 7, 6 for target 11 and 0 for target 12. The cost is the same as for the longest: O(n) time and O(1) extra space.
7 What the window keeps
So far the window kept one number, its total. Other rules need other state. The loop stays the same, and only three things change: what happens when a value enters, what happens when one leaves, and the test.
| Rule for the window | What it keeps | The test |
|---|---|---|
| Total at most k, positive values | the total | broken when total > k |
| At most k zeros | the number of zeros | broken when zeros > k |
| No letter twice | a count for each letter | broken when the new letter's count is 2 |
| At most k different letters | a count map, whose size is the number of letters | broken when size > k |
| Holds every letter of a second string | the counts still needed, and how many letters are missing | good when missing is 0 |
The last rule asks for the shortest window, so it records inside the shrink. The others ask for the longest.
A count map needs care when a value leaves. When a letter's count falls to 0, that letter is no longer in the window, so we delete its entry. Here the rule is at most 2 different letters, and c has just entered:
If a stayed in the map with a count of 0, the map's size would still say 3. The loop would throw out b and c as well, and then run past the end of the window.
8 Mistakes, and when to use it
- Recording in the wrong place. For the longest, a record before the shrink counts broken windows. On our array with limit 6, it returns 5, the broken window [1, 1, 3, 1, 3]. For the shortest, a record after the shrink sees windows that are no longer good. With target 7, it returns 1.
- Moving
lwithout removing its value. The total never goes down, so thewhilenever ends, and the program gets TLE. Any array whose total goes over the limit shows it. - Keeping map entries at 0. The map's size then counts letters that have left. On
"aabc"with at most 2 letters, the window throws out everything. - A negative value. A window that grows can then get a smaller total, so a broken window can become valid again, and the staircase falls apart. The prefix sums lesson showed this on [1, 5, −3]: the window drops 5 before the −3 arrives. The running-sum map from that lesson handles negatives.
The sign is a question about the longest or shortest substring or subarray that meets a rule. Before using the window, check the rule against the grid:
- The longest valid window. A broken window must stay broken as it grows. Grow, shrink while broken, then record.
- The shortest good window. A good window must stay good as it grows. Grow, then record and shrink while good.
- A window of fixed size. Add one value, remove one value, record.
- How many windows meet the rule. The next lesson counts them, with "at most K" minus "at most K − 1".
l never has to move back, and one pass is enough.Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.