Learn the pattern · ~15 min
Monotonic Deque
also called monotonic queue, sliding window maximum
Keep a deque of indices whose values fall from front to back. A newcomer throws out older, no-bigger values from the back; an index that has left the window drops off the front. What remains at the front is the window's max.
Reach for it when you read
- +The max or min of every window of k consecutive elements: sliding window maximum, "best score in the last k matches".
- +
dp[i]needs the bestdp[j]among the last k positions: "jump at most k steps", "chosen elements at most k apart". - +A window whose two ends only move forward, and the condition needs its current max or min: "longest subarray with max − min ≤ limit".
- +Your brute force has an inner loop that rescans the last k elements for the biggest or smallest.
- +Shortest subarray with sum ≥ K when numbers can be negative: prefix sums plus a deque of candidate starts.
Not this one when
- ×The nearest bigger or smaller element, with no window: nothing ever expires, so one open end is enough. That's a monotonic stack.
- ×The median or k-th largest of each window: the deque throws away elements you still need. Use two heaps or an ordered multiset.
- ×The max over arbitrary ranges
[l, r]asked in any order: the ends don't only move forward. Use a sparse table or a segment tree.
Learn Monotonic Deque
First, what's a monotonic deque?
A deque (say "deck", short for double-ended queue) is a list you can add to and remove from at both ends: push_back, pop_back, push_front, pop_front.
Monotonic means it stays sorted. Here the values only fall from front to back: 6, 4, 2 is fine, 6, 2, 4 isn't (4 is bigger than the 2 before it).
So a monotonic deque is a monotonic stack (pop from the back to stay sorted) with a second exit at the front, for elements that have become too old.
How do we keep it falling while a window slides?
Take [5, 3, 4, 1, 2, 6, 0] and a window of k = 3 positions: at index i it covers i − 2 to i. Walk left to right with two rules:
Before pushing the new number, pop from the back every number smaller than or equal to it. After pushing, pop the front if its index has left the window.
| i | number | what happens | deque (values) | indices |
|---|---|---|---|---|
| 0 | 5 | empty: push | 5 | 0 |
| 1 | 3 | back is 5, bigger: push | 5, 3 | 0, 1 |
| 2 | 4 | back is 3 ≤ 4: pop it. Back is 5, bigger: push | 5, 4 | 0, 2 |
| 3 | 1 | back is 4, bigger: push. Front is index 0, outside 1..3: pop it | 4, 1 | 2, 3 |
| 4 | 2 | back is 1 ≤ 2: pop it. Back is 4, bigger: push | 4, 2 | 2, 4 |
| 5 | 6 | 2 and 4 are both ≤ 6: pop both, push | 6 | 5 |
| 6 | 0 | back is 6, bigger: push | 6, 0 | 5, 6 |
Every row falls from front to back, and every index in it is inside the current window.
The code for it
deque<int> dq; // indices; values fall front → back
for (int i = 0; i < n; i++) {
while (!dq.empty() && a[dq.back()] <= a[i])
dq.pop_back(); // smaller ones at the back would break the order
dq.push_back(i);
if (dq.front() <= i - k)
dq.pop_front(); // too old: out of the window
}You don't need to memorise this. It's the table: pop the smaller ones from the back, push, drop the front if it's too old.
Why store indices? A value can't tell you how old it is. At i = 3 we knew the 5 had to go only because its index, 0, is at most 3 − 3. And why an if at the front, not a while? Each step exactly one index, i − k, leaves the window. If it's still in the deque it's at the front, because the front is the oldest.
Fine, but how does this help us?
The classic: Sliding Window Maximum. Report the biggest number in every window of size k. For [5, 3, 4, 1, 2, 6, 0] and k = 3:
| window | numbers | look for the biggest | max |
|---|---|---|---|
| 0..2 | 5, 3, 4 | 5 beats 3 and 4 | 5 |
| 1..3 | 3, 4, 1 | 4 beats 3 and 1 | 4 |
| 2..4 | 4, 1, 2 | 4 beats 1 and 2 | 4 |
| 3..5 | 1, 2, 6 | 6 beats both | 6 |
| 4..6 | 2, 6, 0 | 6 beats both | 6 |
So the answer is [5, 4, 4, 6, 6].
The brute force
For every window, scan its k numbers:
vector<int> windowMaxSlow(const vector<int>& a, int k) {
vector<int> res;
for (int i = 0; i + k <= (int)a.size(); i++)
res.push_back(*max_element(a.begin() + i, a.begin() + i + k));
return res;
}That's n − k + 1 windows times k numbers. With n = 10⁵ and k = 5 × 10⁴, it's about 5 × 10⁴ × 5 × 10⁴ = 2.5 × 10⁹ steps. Compiled with -O2 that took 0.8 s on a laptop: right at the edge of a one-second limit. At n = 2 × 10⁵ it took 3 s.
The one thought that fixes it
Stop at index 2, the number 4. Right before it sits a 3, at index 1.
Think about any window that still holds the 3 from now on. Windows are consecutive, and this one ends at index 2 or later, so it also holds the 4. And 4 is bigger. So the 3 can never be the max of a future window. It's useless from the moment the 4 arrives: pop it. That's the back rule.
The 5 at index 0 is different. It's bigger than the 4, so it can still win, and for window 0..2 it does. Keep it. But it's older than the 4, so it will leave the window first.
So the deque holds exactly the numbers that can still be some window's max, falling from front to back, and the front is the biggest. The only catch is that the front can be too old, and the front rule handles that. After both rules, the front is the window's max.
Equal values: popping on <= throws out an older equal number, because the newer one is just as big and stays longer. Popping on < keeps both, and that's correct too: the older copy expires first, and the equal copy behind it takes over. On [4, 4, 1, 0] with k = 2, both give [4, 4, 1]. <= keeps the deque shorter.
vector<int> windowMax(const vector<int>& a, int k) {
deque<int> dq; // indices; values fall front → back
vector<int> res;
for (int i = 0; i < (int)a.size(); i++) {
while (!dq.empty() && a[dq.back()] <= a[i])
dq.pop_back(); // beaten: older and not bigger
dq.push_back(i);
if (dq.front() <= i - k)
dq.pop_front(); // expired: out of the window
if (i >= k - 1)
res.push_back(a[dq.front()]); // the front is the max
}
return res;
}Dry run
Same array, k = 3. Answers start once the first window is full, at i = 2.
| i | number | popped from back | expired from front | deque (values) | window max |
|---|---|---|---|---|---|
| 0 | 5 | 5 | |||
| 1 | 3 | 5, 3 | |||
| 2 | 4 | 3 | 5, 4 | 5 | |
| 3 | 1 | 5 | 4, 1 | 4 | |
| 4 | 2 | 1 | 4, 2 | 4 | |
| 5 | 6 | 2, 4 | 6 | 6 | |
| 6 | 0 | 6, 0 | 6 |
[5, 4, 4, 6, 6], the same answer as the brute force. Look at i = 3: the 5 was still the biggest, but its window had passed. Forget the expiry check and you get [5, 5, 5, 6, 6].
Why it's O(n)
There's a while inside a for, but count what happens to each index: it's pushed once and popped at most once, from one end or the other. That's at most 2n deque operations: O(n) time. The deque never holds more than the window: O(k) space.
From O(nk) down to O(n), by throwing away numbers that can never be a window's max again.
Window minimum? Flip the comparison
Pop the back while it's bigger than or equal to the new number. Now the values rise from front to back, and the front is the smallest.
while (!dq.empty() && a[dq.back()] >= a[i]) dq.pop_back();On the same array: [3, 1, 1, 1, 0].
A window that grows and shrinks? Two deques
Longest Continuous Subarray With Absolute Diff ≤ Limit: the longest window whose max − min is at most limit. Its ends only move forward, so keep a falling deque for the max and a rising one for the min. When the gap is too big, move the left end forward and expire whatever falls behind it.
int longestSubarray(vector<int>& a, int limit) {
deque<int> mx, mn; // max at mx's front, min at mn's front
int left = 0, best = 0;
for (int i = 0; i < (int)a.size(); i++) {
while (!mx.empty() && a[mx.back()] <= a[i]) mx.pop_back();
while (!mn.empty() && a[mn.back()] >= a[i]) mn.pop_back();
mx.push_back(i); mn.push_back(i);
while (a[mx.front()] - a[mn.front()] > limit) {
left++; // shrink from the left
if (mx.front() < left) mx.pop_front();
if (mn.front() < left) mn.pop_front();
}
best = max(best, i - left + 1);
}
return best;
}On [10, 1, 2, 4, 7, 2] with limit 5 it returns 4: the window 2, 4, 7, 2.
Best of the last k DP values? Same deque
In Jump Game VI, dp[i] = a[i] + max(dp[i − k], …, dp[i − 1]). That max is a sliding window maximum over dp: keep dp indices in the deque, expire the front if it's below i − k, read it to get dp[i], then drop the smaller values from the back and push i.
Remember this
- "The max or min of every window of size k", or "the best value among the last k": a monotonic deque.
- Two exits: expire old indices from the front, drop beaten values from the back.
- Store indices: values tell you who wins, indices tell you who's too old.
- The front is the answer only after you drop the expired front.
<or<=when popping the back: both work.
Practise it on Sliding Window Maximum, then Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit (two deques), Jump Game VI and Constrained Subsequence Sum (best of the last k DP values), and Shortest Subarray with Sum at Least K (prefix sums with negatives).
Below, watch Sliding Window Maximum run line by line.
Watch it work, line by line
Sliding Window Maximum ↗, a = [5, 3, 4, 1, 2, 6, 0], k = 3 → [5, 4, 4, 6, 6]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
Break it
Each card changes one line of the template the way it usually goes wrong in an interview. Before you open it, guess what the broken version prints.
Delete the front check (if (dq.front() <= i - k) dq.pop_front();)
on a = [5, 3, 4, 1, 2, 6, 0], k = 3
What goes wrong?
if (dq.front() <= i - k) dq.pop_front();)broken → [5, 5, 5, 6, 6]
correct → [5, 4, 4, 6, 6]
Index 0 (score 5) never leaves, so it stays at the front for windows [1, 3] and [2, 4], which don't contain it. It's the running-best mistake with extra steps.
dq.front() <= i - k → dq.front() < i - k
on a = [5, 3, 4, 1, 2, 6, 0], k = 3
What goes wrong?
dq.front() <= i - k → dq.front() < i - kbroken → [5, 5, 4, 6, 6]
correct → [5, 4, 4, 6, 6]
Index i − k has just left, but < keeps it one more slide. At i = 3 the window [1, 3] still reports index 0's 5.
while → if in the back pop
on a = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
What goes wrong?
while → if in the back popbroken → [3, 3, -1, 5, 5, 7]
correct → [3, 3, 5, 5, 6, 7]
At i = 4 the 5 pops only the −3 and leaves the −1 in front of it. Index 1 then expires, the −1 becomes the front, and it's reported as the max of [−1, −3, 5].
i >= k - 1 → i >= k
on a = [5, 3, 4, 1, 2, 6, 0], k = 3
What goes wrong?
i >= k - 1 → i >= kbroken → [4, 4, 6, 6]
correct → [5, 4, 4, 6, 6]
The first full window ends at index k − 1 = 2. Starting one step late skips it, so its max, 5, is never recorded.
When to use it, and when not
Ask yourself
Do I need the best (max or min) of a range whose two ends only move forward, so old elements expire at one end while newcomers knock out weaker ones at the other? (A fixed window, a grow-and-shrink window, or the best
dp[j]among the last k.)
Reach for it when
- +min/max over a sliding window
- +dp[i] = best of dp[j] for j in [i-k, i-1]
- +shortest subarray with sum >= K with negatives
- +n up to 1e6; O(n) needed
It fails when
- ×Next greater/smaller with unbounded lookback, no fixed windowuse Monotonic stack
- ×The window aggregate is a sum, not an extremeuse Prefix sum or a running sum
- ×Arbitrary range extremes on a static arrayuse Sparse table
- ×Arbitrary range extremes with updatesuse Segment tree
- ×Window ends don't both move forward monotonicallyuse Mo's algorithm or segment tree
- ×You need the k-th order statistic in the windowuse Two heaps or ordered set
- ×You think a max-heap works: on
[8,1,1,1,1], k=2 the expired 8 stays on topuse Deque (heap needs lazy deletion, O(n log n))
Looks like it, isn't (and the other way round)
- Shortest Subarray with Sum at Least K looks like Sliding Window, needs this pattern
Negatives break shrinking; keep a monotone deque of prefix sums.
- Max Value of Equation looks like Two Pointers, needs this pattern
Rewriting gives a window maximum of (y - x).
Why this pattern and not another
You need the extreme of a moving fixed-size window (or the best of the last k DP states) in O(1) amortised per step. Only a monotonic deque evicts both dominated elements (back) and expired ones (front) in constant time.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why does the deque store indices, not values?Reveal
To know when the front has left the window:
front <= i − k. A value can't tell you its position.2When does an element leave from the back?Reveal
When a newer element at least as big arrives. The old one is no bigger and leaves the window first, so it is never needed: the newcomer gives the same or a bigger answer.
3Why is it O(n) for any k?Reveal
Each index is pushed once and popped at most once, from one end or the other.
4What are the two ways an index leaves the deque, and from which end?Reveal
Beaten: a newer score at least as big arrives, so it leaves from the back. Expired: it slides out of the window, so it leaves from the front.
Practice ladder
- 1Sliding Window Maximumthe hookHard
- 2Sliding Window Minimumwindow minimumMedium
- 3Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limitmax and min togetherMedium
- 4Jump Game VIbest of the last k DP valuesMedium
- 5Constrained Subsequence Sumbest of the last k DP valuesHard
- 6Maximum Subarray Sum IIprefix sumsHard
- 7Max Value of Equationrewrite the formulaHard
- 8Shortest Subarray with Sum at Least Kprefix sums with negativesHard
Finished Monotonic Deque? Mark it done and Lessgo moves you to the next step.