Monotonic Queues
A monotonic queue is a deque kept in sorted order. It holds only the values that could still be the maximum of a later window: expired values leave from the front, values beaten by a newer, larger one leave from the back, and the front is the current window maximum.
The Problem a Stack Cannot Solve
The standard task is the window maximum: report the largest value in every window of size k as it slides across an array. Recomputing each window costs O(n·k); a heap brings it to O(n log k); a monotonic queue does it in O(n).
Why the usual structures fall short explains the design.
A single max variable fails because the maximum can leave the window. When it does, the next largest value is needed, and the variable kept no other candidates. The same problem stops prefix sums from answering range minimum queries: a max or min cannot be undone the way a sum can.
A monotonic stack fails for another reason. A stack removes the item added last, but a sliding window drops the oldest item. That item is at the bottom of the stack, out of reach.
A heap works but does more than needed. It costs O(log k) per operation and cannot remove a particular expired item, so code uses lazy deletion: leave old entries in and discard them when they reach the top.
What the task needs is removal at both ends: drop beaten candidates from one end and expired ones from the other. That is a deque, and giving its two ends these two jobs is the whole technique. The structure is also called a monotonic deque.
- Window minimum is the mirror image: keep the values increasing instead
- When k = 1 every value is its own answer; when k = n there is one window and one answer
- Practice: sliding window maximum
Two Rules, Applied Every Step
- Expire from the front: if the front index is
<= i - k, it has left the window; pop it. - Filter from the back: while the value at the back is smaller than
nums[i], pop the back. - Push
iat the back. - Read the answer: once
i >= k - 1, the window maximum isnums[front].
The deque holds indices, kept so that their values decrease from front to back. The steps above keep it that way at every index i.
At most one index expires per step, because the window moves by one and every index is different.
The back rule is where the reasoning is. If an earlier value is smaller than the current one, it can never be the maximum of a later window: every window that still holds it also holds the current value, which is larger and leaves later. It is beaten on both counts, so it is dropped for good rather than kept as a fallback.
That double reason, larger and longer-lived, is the correctness argument an exam answer needs. Neither half alone is enough: a larger but older value may leave first, and a newer but smaller one may never matter.
Indices, not values, because the front rule tests position. With values alone there is no way to tell whether the front has left the window.
Popping on <= instead of < is also correct for maximum queries: of two equal values, the later one lasts longer and serves just as well, and the deque stays shorter. The code on this page uses <.
For the sliding window minimum, flip the comparison and keep the deque increasing. Everything else stays the same.
- Expire before reading the answer, or an index that has just left can be reported
- Push before reading too, so the newest value can be the answer for its own window
- The deque can hold fewer than k indices; one large value can beat everything else in the window
Why the Front Is Always Correct
After the steps run, the value at the front index is the maximum of the current window, available in O(1). Here is why.
The front rule leaves only indices inside the window. The back rule keeps their values decreasing, so the front holds the largest of them. What remains is to show that nothing was thrown away that should have been kept.
The back rule removes an item only when a larger item arrives later. From then on, any window holding the removed item also holds the larger, later one. So the removed item could not have been the maximum of any remaining window, and removing it loses nothing.
Together: the deque holds exactly the items that could still be the maximum of some future window, in decreasing order. Its front is therefore the current maximum. These items are often called the candidates.
One picture helps: the deque is a falling staircase with the tallest step at the front. Each new arrival knocks down every shorter step behind it, and the moving window wears steps away from the front.
The deque is not the window. It is a subset: the window may hold k items while the deque holds one, if that item beats all the others. It never holds more than k entries, so the space is O(k).
- On strictly increasing input the deque never holds more than one index
- On strictly decreasing input nothing is popped from the back, and only expiry keeps the deque at k
- The tracer below shows both rules on [1, 3, −1, −3, 5, 3] and the wrong answers when expiry is skipped
Terms, operations, and practical uses
Core concept
- Deque FoundationA deque is needed because items leave from the back (beaten) and from the front (expired).
- Sorted InvariantThe values at the stored indices are kept decreasing (for a maximum) or increasing (for a minimum) from front to back.
- ExpirationRemoving the front index once it is outside the window, that is when it is <= i - k.
Maintenance operations
- Push Back (Purge)Before pushing, removing smaller values from the back, since a larger and newer value means they can never be the maximum again.
- Pop Front (Expire)Checking whether the front index has left the window and removing it.
- Front AccessReading the current window maximum (or minimum) from the front of the deque in O(1).
Algorithmic uses
- Sliding Window MaximumThe standard use: given an array and a window size k, find the maximum of every window in O(n).
- Shortest Subarray with Sum at Least KA monotonic deque over prefix sums handles negative numbers, which break the two-pointer window.
- Dynamic Programming OptimizationRecurrences that take a max over the last k states drop from O(n·k) to O(n).
Code in Python, C++ and Java
from collections import deque
def maxSlidingWindow(nums, k):
q = deque() # Stores indices
ans = []
for i, n in enumerate(nums):
# Expire old elements
if q and q[0] < i - k + 1:
q.popleft()
# Maintain monotonic decreasing property
while q and nums[q[-1]] < n:
q.pop()
q.append(i)
# Record max once window is fully formed
if i >= k - 1:
ans.append(nums[q[0]])
return ans
print('Maxes:', maxSlidingWindow([1, 3, -1, -3, 5, 3], 3))#include <iostream>
#include <vector>
#include <deque>
using namespace std;
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> q;
vector<int> ans;
for (int i = 0; i < nums.size(); i++) {
if (!q.empty() && q.front() < i - k + 1) q.pop_front();
while (!q.empty() && nums[q.back()] < nums[i]) q.pop_back();
q.push_back(i);
if (i >= k - 1) ans.push_back(nums[q.front()]);
}
return ans;
}
int main() {
vector<int> nums = {1, 3, -1, -3, 5, 3};
vector<int> ans = maxSlidingWindow(nums, 3);
cout << "Maxes: [";
for (size_t i = 0; i < ans.size(); i++) { if (i) cout << ", "; cout << ans[i]; }
cout << "]\n";
}import java.util.*;
class Main {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> q = new ArrayDeque<>();
int[] ans = new int[nums.length - k + 1];
int ansIdx = 0;
for (int i = 0; i < nums.length; i++) {
if (!q.isEmpty() && q.peekFirst() < i - k + 1) q.pollFirst();
while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) q.pollLast();
q.offerLast(i);
if (i >= k - 1) ans[ansIdx++] = nums[q.peekFirst()];
}
return ans;
}
public static void main(String[] args) {
int[] ans = new Main().maxSlidingWindow(new int[]{1, 3, -1, -3, 5, 3}, 3);
System.out.println("Maxes: " + Arrays.toString(ans));
}
}Step through it
Running on nums = [1, 3, -1, -3, 5, 3], k = 3; then [5, 4, 3, 2], k = 2
Cost, and Where the Pattern Appears
The cost argument matches the monotonic stack's. Each index is pushed exactly once, in its own iteration, and popped at most once, from either end. So the total number of removals over the whole run is at most n, however many happen in a single step.
The inner while loop therefore does O(n) work in total, not O(k) per step, and the algorithm is O(n) time and O(k) space.
Compared with the alternatives: brute force is O(n·k); a heap with lazy deletion is O(n log k) time and up to O(n) space, since old entries pile up; a balanced BST used as a multiset is O(n log k). The monotonic deque beats them on both time and space.
The pattern reaches beyond the window maximum. Whenever a sliding window needs the largest or smallest value it contains, and that value cannot be updated by subtracting what leaves, a monotonic deque is the tool.
Shortest subarray with sum at least k, on an array that may contain negative numbers, is the important case. The ordinary two-pointer window fails there, because negative numbers mean a longer window can have a smaller sum. The fix runs a monotonic deque over the prefix sums, kept increasing.
Dynamic programming with a window is the other family: recurrences such as dp[i] = max(dp[j]) + cost where j ranges over the last k positions. Taking that max naively makes the DP O(n·k); a monotonic deque makes it O(n). Jump-game variants with a maximum jump length are the common example.
Use collections.deque in Python and ArrayDeque in Java; both give O(1) at each end. A Python list with pop(0) makes every front removal O(n) and brings back the slow behaviour the technique was meant to avoid.
- C++:
std::deque<int>withpush_back,pop_back,pop_front,front - If only the maximum of the whole stream is needed, with nothing leaving, a single variable is enough
- A related stack problem: maximum of minimum for every window size uses previous and next smaller elements