Stacks and monotonic stacks
A stack holds the items still waiting for an answer; a monotonic stack pops every item the new one beats, so 'next greater or smaller' problems drop from O(n²) to O(n).
How it works
- Use a stack when the latest open item must close first: brackets, undo, expression parsing.
- A popped item has found its answer: the element that popped it is its next greater.
- Each index is pushed once and popped at most once: O(n) total, despite the nested loop.
- Store indexes, not values, so you can compute distances and widths.
- A monotonic deque also drops the front as the window slides: sliding window max in O(n).
Check yourself
Answer to mark it learned; your answers aren't scored.
Interview prompt: for each day's stock price, return how many consecutive days up to and including today had a price ≤ today's (the stock span). n = 10⁵ and your nested loop times out. What do you reach for?
Go deeper
Solve it in Python 10
- Brackets that close in ordereasy
- Convoys at the finish linemedium
- Days until a warmer daymedium
- Next greater value around a circlemedium
- Smallest number after removing k digitsmedium
- Sum of every run's minimummedium
- Largest rectangle under barshard
- Longest well-formed parentheses stretchhard
- Maximum of every windowhard
- How many people each person can seehard
Full explanation
A stack is last-in, first-out: push and pop at one end in O(1). Use it when the most recent open item must close first: matching brackets, undo, expression parsing, iterative DFS.
A monotonic stack keeps its items in sorted order. Before pushing x, pop every item that x beats. Each popped item has just found its answer: x is its next greater element. Every index is pushed once and popped at most once, so the pass is O(n) instead of the O(n²) of checking every pair.
Store indexes, not values: you usually need distances (days until a warmer day) or widths (largest rectangle in a histogram).
A monotonic deque applies the same rule at the back and also drops the front when its index leaves the window. The front is then always the window's maximum: sliding window maximum in O(n).
Code Next greater element, sliding window max, balanced brackets
from collections import deque
def next_greater(nums: list[int]) -> list[int]:
ans, stack = [-1] * len(nums), [] # stack: indexes, values decreasing
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
ans[stack.pop()] = x # x is the first greater value for that index
stack.append(i)
return ans
def window_max(nums: list[int], k: int) -> list[int]:
dq, out = deque(), [] # dq: indexes, values decreasing
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop() # smaller and older: never a max again
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # front slid out of the window
if i >= k - 1:
out.append(nums[dq[0]])
return out
def balanced(s: str) -> bool:
pairs, stack = {")": "(", "]": "[", "}": "{"}, []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs and (not stack or stack.pop() != pairs[ch]):
return False
return not stackReal example
Daily temperatures: for each day, how many days until a warmer one? [73, 74, 75, 71, 69, 72, 76, 73] → [1, 1, 4, 2, 1, 1, 0, 0]. Keep a stack of indexes with decreasing temperatures. Day 72 pops 69 (1 day) and 71 (2 days); day 76 pops 72 and 75 (4 days). The last two days stay in the stack: answer 0. With 10⁵ days, brute force is ~5·10⁹ pair checks; the stack does at most 2·10⁵ pushes and pops.
Trade-offs +2 · −2
+ You gain
- O(n) for 'next greater/smaller', spans and histogram areas that look O(n²).
- Tiny code: one list and one
whileloop.
− You pay
- Easy to get the comparison wrong (
<vs<=) and mishandle duplicates. - Hard to spot: the problem statement almost never says 'stack'.
Use it when
Matching or nesting (brackets, tags, undo); 'nearest greater or smaller to the left/right' for each element; spans and histogram areas; the max or min of every sliding window.
Avoid it when
When you need the k-th largest or other order statistics (Heaps and top-K), or when items leave the window in arbitrary order, not just from the old end.
Numbers to know 4
- Time O(n): each index is pushed once and popped at most once (≤ 2n operations).
- Space O(n) worst case: a strictly decreasing input never pops.
- Sliding window max: O(n) with a deque, O(n log n) with a lazy-deletion heap, O(n·k) brute force.
- Python:
list.pop()at the end is O(1),list.pop(0)is O(n); usecollections.dequefor both ends.
Common pitfalls 4
- Storing values instead of indexes, then needing the distance or the width.
- Wrong strictness:
<vs<=decides which side owns equal values. Test with duplicates. - Forgetting the indexes left in the stack at the end: they have no answer (-1 or 0).
- Sliding window: using
ifinstead ofwhilewhen popping smaller values, which breaks the order.
Interview questions 3
Answer out loud first, then reveal.
How do you recognize a monotonic stack problem?Show answer
The prompt asks, for each element, for the nearest bigger or smaller element to the left or right, or for spans, visibility, or areas bounded by the shortest bar. The brute force is a nested loop scanning outward from each element. That shape usually collapses to O(n) with a monotonic stack. Then I decide three things: increasing or decreasing, strict or not, and which direction to scan.
What variants do you know?Show answer
Next greater uses a decreasing stack; next smaller, an increasing one. Previous greater is read at push time instead of pop time. Circular arrays loop twice, using i % n. Largest rectangle in a histogram computes a width on every pop. Sum of subarray minimums counts each element's contribution from its left and right boundaries. Sliding window max adds a deque that evicts the front by index.
Sliding window maximum: why a deque and not a heap?Show answer
A heap needs lazy deletion for values that left the window, and stale values pile up, so it is O(n log n). The deque gives O(n): when a value arrives, every smaller value behind it can never be the maximum again, so I drop it. The front is always the current max, and I pop it only when its index leaves the window. I keep the heap for cases where items leave in arbitrary order.