Monotonic Queue
A deque that keeps the window’s maximum or minimum at the front.
- inside the window
- active this step
- result
First window [1, 3, −1]
3 pushed 1 out from the back. Deque values: 3, −1. The max is 3.
VARIABLES
- i
- 2
- deque values
- [3, -1]
- out
- [3]
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Store indices in a deque with decreasing values. Pop smaller values from the back when a new one arrives, and pop the front when it slides out of the window.
Why it matters
Sliding window maximum drops from O(n × k) to O(n), because each index enters and leaves the deque once.
Think of it like this
A leaderboard that only keeps players who could still become number one before they age out.
Use it when
- Maximum or minimum of every window of size k
- DP that needs the best value in a sliding range
- Shortest subarray with sum at least k (with prefix sums)
Avoid it when
- Fixed windows where a running sum is enough
- You need the median - use two heaps
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Monotonic deque | O(n) | O(k) |
| Scan each window | O(n × k) | O(1) |
| Heap with lazy deletion | O(n log n) | O(n) |
Often confused with: heaps - they also give the max, but removing expired items is awkward and costs O(log n).
How to recognize it
Clues in interview prompts that point straight to this pattern.
- The front of the deque is always the current answer
- Pop the front once its index ≤ i − k
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Storing values instead of indices, so you can’t tell when the front expires
- Forgetting to pop expired indices from the front
- Mixing < and <= inconsistently with duplicates
Edge cases to test
- k = 1 - the output equals the input
- k equals the array length
- Decreasing input - the deque fills up to k
Knowledge check
Quick check to lock in the intuition.
What sits at the front of the deque?
Practice
Apply what you just watched on real interview problems.