Keep the largest and smallest of a moving window in a deque, and use it for limits on spread and jumps with a reach.
A monitoring dashboard shows the slowest and the fastest response time of the last five minutes. A new reading arrives every minute, and the oldest reading drops out of the window. An alert fires when the gap between the slowest and the fastest is above a limit.
Rescanning the last five minutes for each new reading works. But a dashboard may look at the last day, which is 1,440 readings, for thousands of services. You need the extremes without scanning the window again.
You already know part of the answer. A monotonic stack removes weaker values from one end, and queues and deques showed the maximum of every window with a deque. This lesson goes further. It uses two deques for both extremes, a window that changes size, and totals that you compute as you go.
A table-tennis title lasts three rounds. Players join a line in the order they arrive. When a stronger player arrives, every weaker player at the back of the line goes home. They can never be champion while the newcomer is still in the line, because the newcomer will stay longer.
The player at the front of the line is the champion. When the champion's three rounds are over, they leave, and the next player in line is champion. The line is the deque, the strength is the value, and the three rounds are the window.
A title lasts three rounds: a stronger newcomer sends weaker players home, and the front of the line is the champion.
A value can only be the maximum of the window if no later value in the window is larger. So keep a deque of positions whose values fall from the front to the back. Each value in it is larger than everything after it in the window.
The front is the largest value of the window. The values behind it are the ones that would take over, in order, if the front left. A second deque, whose values rise from the front to the back, does the same for the smallest value.
Step by step: A deque of window positions, on a ring and on a linked list. The animated player loads in your browser.
Predict what happens
Q A window holds the readings 8, 5, 9, 4, 6 in that order. Which positions are in the deque that tracks the maximum?
Answer: C
A position stays only if every value after it is smaller. The reading 9 is larger than 4 and 6, and 6 is the last reading. Readings 8, 5 and 4 each have a larger value after them, so they can never be the maximum.
A new value removes weaker positions from the back of the deque. Then its own position joins at the back. Take the stream 5, 3, 4, 1, 6, 2 and a window of 3.
The 5 joins the empty deque. The 3 is smaller, so it joins behind the 5. The 4 removes the 3, because 3 can never be the maximum while 4 is in the window. The deque now holds the positions of 5 and 4.
A new value removes every weaker position from the back of the deque, then joins. The front stays the largest value.
Step by step: A new value of 7 removes the weaker values from the back. The animated player loads in your browser.
Predict what happens
Q The deque holds the readings 9, 6 and 4, from the front to the back. The reading 7 arrives. What does the deque hold after it joins?
Answer: C
The back is trimmed while it is at most the new value. 4 and 6 are smaller than 7, so they leave. 9 is larger, so it stays at the front, and 7 joins behind it.
The front leaves when its position slides out of the window. A window of 3 that ends at position i starts at i - 2, so a position i - 3 or earlier has left. Check the front after the new value joined, and remove it if it is out.
In the stream above, the 5 is at position 0. When the 1 arrives at position 3, the window is positions 1 to 3. The 5 has left, and the front becomes the 4.
Exercise · Find the bug: The maximum that stays one step too long. This function returns the maximum of every window of k values. Some answers are a window late: an old maximum stays after it has left. Which line is wrong?
def window_max(nums, k):
window = []
result = []
for i in range(len(nums)):
while window and nums[window[-1]] <= nums[i]:
window.pop()
window.append(i)
if window[0] < i - k:
window.pop(0)
if i >= k - 1:
result.append(nums[window[0]])
return resultThe front leaves when its position slides out of the window. A window of three that ends at i starts at i minus 2.
Step by step: The front leaves when it slides out of the window. The animated player loads in your browser.
Predict what happens
Q A window of 4 ends at position 9, and the deque front holds position 5. What happens?
Answer: B
A window of 4 ending at 9 starts at 9 - 4 + 1 = 6. Position 5 is out of the window, so it is removed from the front. The next position takes over.
Exercise · Put it in order: The sliding window maximum. Arrange the lines into a function that returns the maximum of every window of k values, using a deque of positions.
def window_max(nums, k):
window = deque()
result = []
for i in range(len(nums)):
while window and nums[window[-1]] <= nums[i]:
window.pop()
window.append(i)
if window[0] <= i - k:
window.popleft()
if i >= k - 1:
result.append(nums[window[0]])
return result
while window and nums[window[-1]] >= nums[i]:
window.append(nums[i])The front of the falling deque is the maximum and the front of the rising deque is the minimum. Reading either costs O(1). For the same stream and a window of 3, the maximums are 5, 4, 6 and 6, and the minimums are 3, 1, 1 and 1. So the spreads are 2, 3, 5 and 5.
Exercise · Break it: Find the window whose minimum is stale. This function gives the spread (largest minus smallest) of every window of k readings, with one deque for each extreme. Find an input where it gives the wrong answer.
from collections import deque
def window_spreads(readings, k):
highest, lowest, spreads = deque(), deque(), []
for i, x in enumerate(readings):
while highest and readings[highest[-1]] <= x:
highest.pop()
highest.append(i)
while lowest and readings[lowest[-1]] >= x:
lowest.pop()
lowest.append(i)
if highest[0] <= i - k:
highest.popleft()
if i >= k - 1:
spreads.append(readings[highest[0]] - readings[lowest[0]])
return spreadsEach position joins each deque once and leaves it at most once. For these six values, the two deques make 20 steps in all. The count grows with n, not with the window width.
Two deques give both extremes: a falling one for the maximum and a rising one for the minimum. Their fronts give the spread.
Step by step: The maximum of every window of 3. The animated player loads in your browser.
Predict what happens
Q You run the window of 3 over a stream of 1,000 values. The window width changes to 300. What happens to the number of deque steps?
Answer: C
Each position joins the deque once and leaves it at most once. So the pass is O(n) for any window width. A rescan would cost about n times the width.
Exercise · Predict the output: The maximum of each window. A deque of positions tracks the maximum of every window of 3. What does this print?
from collections import deque
nums = [4, 2, 7, 3, 5, 1]
k = 3
window = deque()
out = []
for i in range(len(nums)):
while window and nums[window[-1]] <= nums[i]:
window.pop()
window.append(i)
if window[0] <= i - k:
window.popleft()
if i >= k - 1:
out.append(nums[window[0]])
print(*out)A limit on the spread gives a window whose width changes. The right edge moves one value at a time. The left edge moves right while the spread is above the limit. For the readings 8, 5, 9, 4, 6, 7, 3 and a limit of 3, the longest steady run is 3 readings: 4, 6, 7.
Both deques drop positions that are before the left edge. The left edge only moves right, so every position still leaves each deque at most once. To count the runs, add right - left + 1 at each right edge. Every start from the left edge to the right edge gives a steady run.
A deque can also hold totals that you compute as you go. Say best[i] is the best total of a route that ends at checkpoint i, with a jump of at most 3 checkpoints. Then best[i] is the points of i plus the largest best among the previous 3 checkpoints. That is a window maximum over numbers you built a moment ago.
For the points 2, -4, 6, -1, -3, 5, the totals are 2, -2, 8, 7, 5 and 13. The deque holds positions whose totals fall, and its front gives the best place to jump from.
Suppose a task asks for the shortest run with a sum of at least a target, and numbers can be negative. A window that grows and shrinks fails.
Write the prefix totals instead. A run is the difference of two prefix totals. A deque of starts whose prefix totals rise finds, for each end, the closest start whose total is at least the target lower.
Not every window question needs a monotonic deque. To find the first refund in each window, keep a plain queue of the positions of refunds, oldest first. Remove expired positions from the front and read the front. Nothing is removed from the back.
Here is the monotonic deque next to two other ways to read the extremes of a window.
| Operation | Monotonic deque | Rescan the window each time | Max-heap with lazy deletion |
|---|---|---|---|
| Add a new value at the back | O(1) amortised: weaker values leave first | O(1): append it | O(log n) |
| Remove the oldest at the front | O(1): drop the front position | O(1): move the left edge | O(log n) later, when it reaches the top |
| Peek at the largest in the window | O(1): the front | O(k): scan the window | O(1) after dropping stale tops |
| Search for a given value | Not possible: weaker values have left the deque | O(k) | O(n) |
| Pop back: remove weaker values | O(1) each, one pop at most for each value | Not needed | Not needed |
| Window maximum for all n values | O(n) | O(n × k) | O(n log n) |
A deque wins when you need the extreme of a sliding window. A heap is better when values leave in any order, and a plain running total is better for a sum.
Now drive the queue yourself. Use the doubly variant for the deque, so both ends cost one step. Use window_max to watch the whole algorithm run.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the window yourself. The lab gives you a WindowExtremes class with two queues of positions. You write seven methods: add, remove_oldest, window_max, window_min, spread, sizes and size.
Four things to take care over:
remove_oldest removes a position from a queue front only when the front holds the position of the leaving value. Compare positions, never values: with two equal values, the older one is already gone from the queue.When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a monotonic deque when you need the largest or smallest value of a window that slides, grows or shrinks from the left. That covers a limit on the spread and the best earlier total within a reach. With prefix totals, it also covers the shortest run that reaches a sum.
Each position joins once and leaves at most once, so the whole pass is O(n).
For the sum or the average of a window, keep a running total. For a count, keep a running count. For the median, use two heaps. If you need the extreme only once, at the end, a single scan or a sort is simpler.
A deque gives only the extreme and a few runners-up. It cannot answer "what is the rank of this value".
A deque of values cannot tell an old equal value from a new one. Take the window 5, 5, where the newer 5 removes the older 5 from the deque. When the oldest value leaves, the front equals 5, so the code removes the front by mistake. The deque is empty, though a 5 is still in the window.
if highest and highest[0] == gone: # wrong: compares values
highest.popleft()
if highest and highest[0] == first: # right: compares positions
highest.popleft()Compare positions, not values. With the window five, five, an equal value can be mistaken for the one that left.
If you only trim the back, an old maximum stays at the front for ever. For the values 9, 1, 1 and a window of 2, the second window holds 1, 1, but the front is still the 9. The code returns [9, 9] and the right answer is [9, 1].
if front <= i - k: # missing: the front may have left the window
deque.popleft()When the spread is too big, the left edge may have to move more than once. An if moves it one place, and a while moves it until the run is steady. For the longest run the shortcut can still give the right length, but for a count it fails. With the readings 3, 5, 0 and a limit of 4, the count is 4 and the shortcut returns 5.
if readings[highest[0]] - readings[lowest[0]] > limit: # wrong
while readings[highest[0]] - readings[lowest[0]] > limit: # rightShrinking a window from the left while its sum is large enough works only for numbers that are not negative. With the changes -2, 1 and a target of 1, the window never drops the -2, so its sum stays below 1. The code says no run reaches the target, but the second value alone does.
while total >= target: # wrong with negative numbers: use prefix totals and a deque
total -= changes[left]right - left + 1 counts the runs that end at the right edge.Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · What the deque holds
Q1/3 A monotonic deque tracks the maximum of a window. What does it hold, and what is at its front?
Answer: B
Each position in the deque has a value larger than everything after it. So the values fall, and the front is the maximum.
Q2/3 The window holds 4, 7, 3, 5 in that order. Which positions does the maximum deque hold?
Answer: C
7 is larger than 3 and 5. 5 is the last value. 4 and 3 each have a larger value after them, so they can never be the maximum.
Q3/3 A new value arrives. Which positions leave the back of the maximum deque?
Answer: C
Those values can never be the maximum while the newer value is in the window, because the newer value stays longer. Larger values stay, since they could win later.
Checkpoint · Expiry and positions
Q1/3 A window of 4 ends at position 9. Which positions are inside it?
Answer: B
A window of 4 ending at 9 starts at 9 - 4 + 1 = 6. So a position at 9 - 4 = 5 or earlier has left.
Q2/3 Why does the deque store positions and not values?
Answer: B
You need the position to know when to expire the front. With equal values, comparing values can remove the wrong entry.
Q3/3 The window 9, 1, 1 has a width of 2, and the code never expires the front. What does it return for the two windows?
Answer: B
The 9 stays at the front and is never removed, so the second window, 1, 1, wrongly reports 9. Expire the front after each new value joins.
Checkpoint · Cost and limits
Q1/4 A pass over n values uses a deque. Why does it cost O(n) although a loop sits inside a loop?
Answer: C
Every position is pushed once and popped at most once. So all the inner loops together cost O(n).
Q2/4 You track the spread of a variable window with two deques. When is the left edge moved?
Answer: B
One move may not be enough. A loop moves the left edge until the run is steady again. An if breaks a count of runs.
Q3/4 For a limit of 3 and the readings 8, 5, 9, 4, 6, 7, 3, how many steady runs end at the reading 7, when the left edge is at position 3?
Answer: C
The left edge is 3 and the right edge is 5, so right minus left plus one is 3: the runs 7, 6, 7 and 4, 6, 7.
Q4/4 You need the median of a sliding window. Which tool fits best?
Answer: C
A deque gives only the extremes and a few runners-up. The median is the middle value, which two heaps keep.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.