Deques & Monotonic Stacks
Data Structures & Algorithms · Linked Lists, Stacks & Queues · Intermediate · 22 min
Use a deque and a monotonic stack to answer 'next greater' and 'maximum of every window' questions in a single O(n) pass.
A pile of unanswered letters, each asking 'when is the next warmer day?'. Every warm morning you answer the cooler letters on top of the pile and throw them away, and the pile always stays sorted from hottest at the bottom to coolest on top.
The idea in everyday words
Think of kids lining up for a photo, each one wanting to know who is the next taller kid to arrive. When a tall kid shows up, every shorter kid at the back of the waiting line gets an answer and steps out. The kids still waiting are always in order from tallest to shortest, so the newcomer only ever needs to look at the last kid in line.
The deque: a line that is open at both ends
A deque (say "deck", short for double-ended queue) is a list where you can add or remove at both ends in O(1) time.
| Operation | Python collections.deque |
Cost |
|---|---|---|
| add at the back | d.append(x) |
O(1) |
| add at the front | d.appendleft(x) |
O(1) |
| remove from the back | d.pop() |
O(1) |
| remove from the front | d.popleft() |
O(1) |
| peek at either end | d[0], d[-1] |
O(1) |
Why not just use a list? list.pop(0) has to shift every other item one slot left, so it costs O(n). A deque is built so both ends are cheap.
A deque can act as a stack (use one end only) or a queue (add at the back, remove at the front). JavaScript has no built-in deque, so people use an array plus a "head" index that moves forward instead of calling shift().
from collections import deque
d = deque([2, 3])
d.appendleft(1) # [1, 2, 3]
d.append(4) # [1, 2, 3, 4]
d.popleft() # removes 1
print(list(d)) # [2, 3, 4]
The question: what is the next greater element?
For every number, find the first number to its right that is bigger. If there is none, the answer is -1.
Example: [2, 1, 5, 3, 6] → [5, 5, 6, 6, -1].
Brute force: for each item, scan to the right until you find something bigger. Two nested loops, so O(n²). With 100,000 items that is about 10 billion steps. Too slow.
The observation that unlocks it: walk left to right and keep the items that are still waiting for an answer. Suppose 5 and then 3 are waiting. When 6 arrives, it answers 3 first (the most recent one), then 5. The waiting items are always in decreasing order: if a smaller item came before a bigger one, the bigger one would already have answered it.
So the waiting list is a stack whose values only go down from bottom to top. That is a monotonic stack (monotonic = always moving in one direction).
The monotonic stack template
def next_greater(nums):
ans = [-1] * len(nums)
stack = [] # indices, values decreasing
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
ans[stack.pop()] = x # x is their next greater
stack.append(i)
return ans
print(next_greater([2, 1, 5, 3, 6])) # [5, 5, 6, 6, -1]
Why is it O(n) when there is a loop inside a loop? Each index is pushed once and popped at most once. Across the whole run the inner while does at most n pops in total. This is called amortized analysis: some steps do a lot, but the total is small.
Store indices, not values. With an index you can read the value (nums[j]) and compute a distance (i - j), which "daily temperatures" needs.
| You want | Keep the stack | Pop while |
|---|---|---|
| next greater | decreasing | top < new |
| next smaller | increasing | top > new |
| previous greater | decreasing | answer = top after popping |
| circular array | loop over the array twice | same rule |
Sliding window maximum with a monotonic deque
Problem: for every window of size k, report the largest value. [1, 3, -1, -3, 5, 3, 6, 7], k = 3 → [3, 3, 5, 5, 6, 7].
Brute force looks at all k items in each window: O(n·k).
Key insight: if a newer item is bigger than an older one, the older one can never be a window maximum again: the newer one is bigger and stays in the window longer. So throw the older one away.
Keep a deque of indices whose values are decreasing from front to back:
- Pop from the back while the back value is ≤ the new value (they are useless now).
- Push the new index at the back.
- Pop from the front if that index has slid out of the window (
index <= i - k). - The front is always the maximum of the current window.
You need a deque, not a stack, because items leave from both ends: useless ones from the back, expired ones from the front. Each index enters and leaves once, so it is O(n).
Where this pattern hides
- Daily temperatures: days until a warmer day (next greater, store the distance).
- Stock span: how many days in a row the price was ≤ today (previous greater).
- Largest rectangle in a histogram: for each bar, find the first smaller bar on each side (increasing stack).
- Trapping rain water and remove k digits also have monotonic stack solutions.
- Shortest subarray with sum at least k and window min/max use a monotonic deque.
The tell: the question asks, for each item, about the nearest item to the left or right that is bigger or smaller, or about the max/min of a moving window.
Step by step
- Start:
temps = [73, 74, 75, 71, 69, 72, 76]. ans = all zeros. The stack holds indices of days still waiting for a warmer day. It is empty.
- Day 0 (73):
Nobody is waiting. Push 0. stack = [0] (73).
- Day 1 (74):
74 > 73, so day 0 is answered: ans[0] = 1 - 0 = 1. Pop it, push 1. stack = [1] (74).
- Day 2 (75):
75 > 74: ans[1] = 1. Pop, push 2. stack = [2] (75).
- Days 3 and 4 (71, 69):
Both are cooler than the top, so nobody is answered. Push both. stack = [2, 3, 4] holding 75, 71, 69: decreasing, as promised.
- Day 5 (72):
72 > 69: ans[4] = 1. 72 > 71: ans[3] = 2. 72 < 75: stop. Push 5. stack = [2, 5] (75, 72).
- Day 6 (76):
76 > 72: ans[5] = 1. 76 > 75: ans[2] = 4. Push 6. stack = [6].
- Done:
Day 6 is still waiting, so it keeps 0. Answer: [1, 1, 4, 2, 1, 1, 0]. Every index was pushed once and popped at most once: O(n).
Code example
from collections import deque
def next_greater(nums):
ans = [-1] * len(nums)
stack = [] # indices whose answer is unknown
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
ans[stack.pop()] = x
stack.append(i)
return ans
def window_max(nums, k):
dq, out = deque(), [] # indices, values decreasing
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop() # smaller values can never win again
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # the front slid out of the window
if i >= k - 1:
out.append(nums[dq[0]])
return out
print("next greater:", next_greater([2, 1, 5, 3, 6, 4]))
print("window max:", window_max([1, 3, -1, -3, 5, 3, 6, 7], 3))Complexity
- Time: O(n): every index is pushed once and popped at most once, so the inner while loop does at most n pops in total
- Space: O(n): in the worst case (a decreasing list) every index waits on the stack
Interview tips
Say the brute force first ('scan right from each index, O(n²)'), then explain what the stack remembers so you never scan twice.
Explain the O(n) with the push-once, pop-once argument. Interviewers often ask 'isn't that nested loop O(n²)?'
State the invariant out loud: 'the stack holds indices whose values are decreasing, and all of them are still waiting for an answer.'
For sliding window maximum, say why it must be a deque: expired indices leave from the front, useless ones from the back.
Likely follow-ups: next greater in a circular array (loop twice with i % n), largest rectangle in a histogram, stock span.
Challenge: Daily Temperatures
Given a list of daily temperatures, return a list where answer[i] is the number of days you have to wait after day i to get a strictly warmer day. If there is no future warmer day, use 0.
Example: daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73]) → [1, 1, 4, 2, 1, 1, 0, 0]
Aim for O(n) with a monotonic stack.
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Daily Temperatures (Medium)
- Next Greater Element I (Easy)
- Sliding Window Maximum (Hard)
- Largest Rectangle in Histogram (Hard)
More in Linked Lists, Stacks & Queues
Previous: Stacks & Queues · Next: Hash Maps (Dictionaries)