Sub topic 10
Sliding-window maximum with a monotonic deque
This chapter assumes you know collections.deque (append, pop, popleft), can read Big-O costs, and are comfortable with enumerate and index arithmetic. It solves one classic problem and shows why a deque fits it.
The problem
Given a list nums and a window size k, report the maximum of every run of k consecutive elements. For [1, 3, -1, -3, 5, 3, 6, 7] and k = 3, the windows are [1, 3, -1], [3, -1, -3], and so on. Their maxima are [3, 3, 5, 5, 6, 7].
The direct approach calls max() on each window. That costs O(k) per window and O(n·k) overall. A monotonic deque brings it down to O(n).
The idea: keep only candidates
Suppose the window holds ... 2, 7 ... and a new value 9 arrives. The 2 and the 7 are older than 9 and smaller, so they will leave the window first. They can never be a maximum again, so we can discard them.
Applying this rule leaves a deque of indices whose values are in decreasing order from front to back. This is the monotonic property. The front is always the current window maximum.
Three rules run for each new element at index i:
- Pop from the back while the back value is less than or equal to the new value.
- Append
iat the back. - Pop from the front if that index has slid out of the window (
index <= i - k).
Once i >= k - 1, the window is complete and nums[window[0]] is the answer for it.
The code
from collections import deque
def sliding_max(nums, k):
window = deque() # indices; their values are in decreasing order
out = []
for i, x in enumerate(nums):
while window and nums[window[-1]] <= x:
window.pop()
window.append(i)
if window[0] <= i - k:
window.popleft()
if i >= k - 1:
out.append(nums[window[0]])
return out
print(sliding_max([1, 3, -1, -3, 5, 3, 6, 7], 3)) # [3, 3, 5, 5, 6, 7]Tracing the run
The table shows the deque contents (as indices) after each step for k = 3.
| i | x | Deque after step | Output so far |
|---|---|---|---|
| 0 | 1 | [0] | none |
| 1 | 3 | [1] | none |
| 2 | -1 | [1, 2] | 3 |
| 3 | -3 | [1, 2, 3] | 3, 3 |
| 4 | 5 | [4] | 3, 3, 5 |
| 5 | 3 | [4, 5] | 3, 3, 5, 5 |
| 6 | 6 | [6] | 3, 3, 5, 5, 6 |
| 7 | 7 | [7] | 3, 3, 5, 5, 6, 7 |
At i = 4, the value 5 removes the indices 3, 2, and 1 from the back in one pass. Those values (-3, -1, 3) are all smaller than 5.
The expiry rule never fires in this trace. Try [5, 4, 3, 2, 1] with k = 3. Each new value is smaller than the back, so nothing is popped from the back. At i = 3 the deque is [0, 1, 2, 3], and index 0 is now outside the window (0 <= 3 - 3). Only the front check removes it, which yields [5, 4, 3].
Why it is O(n)
The while loop looks like it could make the scan quadratic. It doesn't. Each index is appended once and popped at most once, either from the back by a larger value or from the front by expiry. Across the whole scan there are at most n appends and n pops, so the total work is O(n). Extra space is O(k), because the deque holds at most k + 1 indices (briefly k + 1, before the front pop).
A list would break this bound. list.pop(0) shifts every remaining element, which is the cost described earlier in this tutorial. The deque makes both ends O(1).
Common errors
- Storing values instead of indices. You then cannot tell when the front has left the window, and you cannot look up values for comparison cheaply. Store indices and read
nums[index]. - Using
<instead of<=in the back-pop test. The result is still correct, but equal values pile up in the deque. Using<=keeps only the newest of equal values, which is the one that stays longest. - Skipping the output guard. Without
i >= k - 1, you would record partial windows at the start. - Unchecked
k. Withk <= 0the expiry check misbehaves, and withk > len(nums)the function returns an empty list. Validatekat the boundary if callers are untrusted.
Exercise
What does sliding_max([5, 4, 3, 2, 1], 3) return, and which step removes index 0 from the deque?
Show answer
It returns [5, 4, 3]. Nothing is popped from the back because every new value is smaller than the back value. At i = 3 the front index 0 satisfies 0 <= 3 - 3, so the expiry check calls popleft.
Exercise
Why is the total running time O(n) even though a while loop runs inside the for loop?
Show answer
Each index enters the deque once and leaves at most once, so there are at most n appends and n pops over the entire scan. The inner loop's work is spread across iterations and adds up to O(n) in total.