The monotonic deque: the maximum of every window
🌍 In real life. In the monsoon, a flood office on the Jamuna reads the river level every hour and warns villages using the highest level in the last 3 hours. Re-reading the last 3 numbers every hour works, but a clever clerk keeps a short list instead. When a new, higher reading comes in, every older reading that is not higher is crossed out: it can never again be the highest of any 3 hours that include the new one. Old readings at the front are crossed out once they are more than 3 hours old. The first reading on the list is always the answer.
The idea in one sentence: keep a deque of the positions in the window that could still be its maximum, their numbers falling from front to back; a new number first removes every smaller-or-equal number from the back, joins the back, and the front leaves once it falls out of the window: the front is always the window's maximum.
Its words:
- monotonic deque: a deque whose numbers only go one way, here falling from front to back
- expire: a position leaves the front when it is no longer inside the window,
dq[0] <= i - k
How it works, step by step, for each position i with number x:
- while the back of the deque has a number
<= x: pop it from the back - append i at the back
- if the front is
<= i - k, it has left the window: popleft it - once
i >= k - 1, the window is full: its maximum isnums[dq[0]]
Watch the river levels, 3 hours at a time:
Why it is correct. A number dropped from the back has a bigger-or-equal number after it in the window. That later number stays in every window the dropped one would still be in (it leaves later), so the dropped one can never be a maximum again: dropping it loses nothing. What is left falls from front to back, so the front is the biggest of the window's candidates. And the front expiry keeps only positions inside the window.
What it costs, worked out. Each position joins the deque once and leaves at most once (from the back or the front), so all the while loops together run at most n times: O(n), however big k is. Re-scanning each window with max(nums[i:i + k]) costs about k comparisons per window, O(n × k): for 10,000 readings and a window of 100, about a million comparisons against about 20,000. The deque holds at most k positions: O(k) memory.
from collections import deque
def window_max(nums, k):
dq = deque() # positions; their numbers fall from front to back
maxes = []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop() # it can never be a maximum again
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # it has left the window
if i >= k - 1:
maxes.append(nums[dq[0]])
return maxes
levels = [4, 7, 5, 3, 2, 8, 6, 9]
print(window_max(levels, 3))
print([max(levels[i:i + 3]) for i in range(len(levels) - 2)]) # the slow checkMistakes and edge cases.
- keeping numbers in the deque instead of positions: you can't tell when the front has left the window
ifinstead ofwhilefor the back: one new big number may need to drop several smaller ones- expiring with
dq[0] < i - k: position i − k is already outside a window of k ending at i - recording a maximum before the first window is full (
i >= k - 1) - for the minimum of every window, flip it: drop numbers
>= x, so the numbers rise from front to back
Quiz
What does this print?
from collections import deque nums, k = [1, 3, 2, 5], 2 dq, maxes = deque(), [] for i, x in enumerate(nums): while dq and nums[dq[-1]] <= x: dq.pop() dq.append(i) if dq[0] <= i - k: dq.popleft() if i >= k - 1: maxes.append(nums[dq[0]]) print(maxes)The deque holds the numbers 7, 5, 3. Why can 5 and 3 be dropped when 6 arrives?
- 6 is bigger and stays in every window they are in, so they can never be a maximum again
- The deque can only hold 2 numbers
- They have left the window
What does the monotonic deque cost for n numbers and a window of k?
- O(n): each position joins once and leaves at most once
- O(n × k): it looks at the whole window each time
- O(k)
window_max([3, 1, 4], 3) gives [3], but 4 is the biggest. Which line is wrong?
from collections import deque def window_max(nums, k): dq, maxes = deque(), [] for i, x in enumerate(nums): if dq and nums[dq[-1]] <= x: dq.pop() dq.append(i) if dq[0] <= i - k: dq.popleft() if i >= k - 1: maxes.append(nums[dq[0]]) return maxes
Coding tasks
Write
window_max(nums, k)in O(n) with a monotonic deque: the maximum of every window of k neighbours, in order (1 ≤ k ≤ len(nums)).Write
window_min(nums, k)in O(n): the minimum of every window of k neighbours, in order (1 ≤ k ≤ len(nums)). For example, the coldest hour in every 3 hours.