Monotonic stack pattern for coding interviews
A monotonic stack keeps indexes whose values only increase (or only decrease) from bottom to top, and pops everything a new value breaks the order for. Each pop answers a question for the popped element, such as "what is the next larger value?", so a whole array is processed in O(n) even though the brute force looks at every pair. Use it for next greater or smaller element, waiting-time questions, spans and the largest rectangle under a bar chart.
By Evin JohnPublished 8 min read
How to spot it
The brute force for these questions has the same shape: for each element, scan right (or left) until you find one that is larger or smaller. That is O(n²) in the worst case, for example on a list that only decreases. The repeated work is that many elements are waiting for the same answer. A monotonic stack holds exactly the elements still waiting. When a new value arrives that is larger than the top, it is the answer for that top element, and possibly for several below it, so they are popped and resolved together. What remains on the stack is always in sorted order, which is where the name comes from.
| Question | Scan | Stack keeps values | Pop when the new value is |
|---|---|---|---|
| Next greater to the right | Left to right | Decreasing | Greater than the top |
| Next smaller to the right | Left to right | Increasing | Smaller than the top |
| Previous strictly greater (spans) | Left to right | Decreasing | At least the top |
| Widest bar range for each height | Left to right | Increasing | Smaller than or equal to the top |
Template: next greater element
For each value, find the first larger value to its right, or -1 if there is none. For [2, 7, 3, 5, 4, 6, 8] the answers are [7, 8, 5, 6, 6, 8, -1]. Walk left to right. While the new value is greater than the value at the top index, pop that index and record the new value as its answer. Then push the new index.
def next_greater(values):
result = [-1] * len(values)
stack = [] # indexes still waiting; values decrease
for i, v in enumerate(values):
while stack and values[stack[-1]] < v:
result[stack.pop()] = v
stack.append(i)
return resultfunction nextGreater(values) {
const result = new Array(values.length).fill(-1);
const stack = [];
for (let i = 0; i < values.length; i++) {
while (stack.length && values[stack[stack.length - 1]] < values[i]) {
result[stack.pop()] = values[i];
}
stack.push(i);
}
return result;
}Changing what you record changes the question. Record i - j instead of the value and you get "how many days until a higher reading": daily temperatures of [31, 30, 34, 33, 32, 36] give [2, 1, 3, 2, 1, 0]. Use a strict comparison (<) when equal values should not count as an answer, and <= when they should.
Shape: spans looking backward
A span asks, for each day, how many consecutive days ending today had a value no higher than today's. Store (value, span) pairs. When today's value is at least the top's, absorb the top's span into today's and pop it, since any future day that beats today also beats everything today absorbed. For prices [21, 18, 19, 25, 17, 22, 30] the spans are [1, 1, 2, 4, 1, 2, 7].
def span(prices):
out, stack = [], [] # (price, span), prices decreasing
for p in prices:
s = 1
while stack and stack[-1][0] <= p:
s += stack.pop()[1]
stack.append((p, s))
out.append(s)
return outShape: largest rectangle under a bar chart
Bars of width 1 stand side by side; find the largest rectangle that fits under them. For each bar, the best rectangle using its full height stretches left and right until a shorter bar. Keep an increasing stack of indexes. When a shorter bar arrives, every taller bar on the stack has found its right limit; its left limit is the index now below it on the stack. Appending a height of 0 at the end flushes whatever remains. For heights [2, 4, 4, 3, 1], the answer is 9: height 3 across the three bars 4, 4 and 3.
def largest_rectangle(heights):
best = 0
stack = [] # indexes with increasing heights
for i, h in enumerate(heights + [0]): # the 0 flushes the stack
while stack and heights[stack[-1]] >= h:
top = heights[stack.pop()]
left = stack[-1] + 1 if stack else 0
best = max(best, top * (i - left))
stack.append(i)
return bestfunction largestRectangle(heights) {
let best = 0;
const stack = [];
for (let i = 0; i <= heights.length; i++) {
const h = i === heights.length ? 0 : heights[i];
while (stack.length && heights[stack[stack.length - 1]] >= h) {
const top = heights[stack.pop()];
const left = stack.length ? stack[stack.length - 1] + 1 : 0;
best = Math.max(best, top * (i - left));
}
stack.push(i);
}
return best;
}A cousin: the monotonic deque for window maximums
To report the maximum of every window of k consecutive values, keep a deque of indexes whose values decrease from front to back. Pop smaller values from the back as each new value arrives, drop the front when it slides out of the window, and read the maximum at the front. For [4, 2, 12, 3, 8, 1, 6] and k = 3 the maximums are [12, 12, 12, 8, 8]. It is O(n), compared with O(n log k) for a heap.
from collections import deque
def window_max(values, k):
dq, out = deque(), [] # indexes; values decrease front to back
for i, v in enumerate(values):
while dq and values[dq[-1]] <= v:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
out.append(values[dq[0]])
return outExample problems to practice
- Next greater element, then the circular version. For a circular list, loop over the indexes twice (i from 0 to 2n - 1, using i mod n) and only push during the first pass.
- Days until a higher reading. Record distances instead of values.
- Running span of prices. The (value, span) stack above.
- Largest rectangle under bars, then the largest rectangle of 1s in a grid. Treat each grid row as the base of a bar chart of column heights.
- Sliding window maximum. The deque variant; compare with the heap approach in the heap and priority queue pattern.
- [Valid Parentheses](/coding-problems/valid-parentheses). Not monotonic, but the best warm-up for thinking about what a stack is holding and when to pop.
Complexity
| Problem | Time | Extra space |
|---|---|---|
| Next greater or smaller for every element | O(n) | O(n) |
| Days until higher, spans | O(n) | O(n) |
| Largest rectangle under bars | O(n) | O(n) |
| Sliding window maximum (deque) | O(n) | O(k) |
| Brute-force scan for comparison | O(n²) | O(1) |
The while loop inside the for loop makes the code look quadratic. It is not: an index can only be popped once after being pushed once, so the total number of pops across the whole run is at most n. Say this when you state the complexity, because interviewers often ask.
Common mistakes
- Storing values instead of indexes, then having no way to compute a distance or width.
- The wrong comparison for duplicates. Decide whether an equal value counts as "greater" and pick < or <= on purpose.
- Forgetting the leftovers. Elements still on the stack at the end have no answer; the default (-1 or 0) must already be in place, or flush with a sentinel.
- Off-by-one widths in the rectangle problem. The left edge is the index below the popped one plus one, or 0 if the stack is empty.
- Calling it O(n²) because of the nested loop, or failing to explain why it is O(n).
How to explain it out loud
Fictional example
- Candidate
- For each day I could scan forward for a higher reading, but on a falling stretch that is quadratic.
- Candidate
- Instead I keep a stack of days still waiting for a higher reading. Their readings decrease from bottom to top, because a higher day would already have resolved the lower ones.
- Candidate
- When a new day is higher than the top, that day is the answer for the top, so I pop it and record the gap, and repeat. Each day is pushed and popped once, so it is linear.
Stack and queue thinking also drives graph traversal patterns, and the window idea connects to the two pointers pattern. Every walkthrough is on the coding problems hub.
Practicing with Natively
Natively can read one of these problems from a screenshot while you practice on Mac or Windows, and suggest whether a monotonic stack applies and which order it should keep, so you can compare its reasoning with your own attempt. Your mock interview is transcribed and saved, which makes it easy to see whether you explained the amortized O(n) argument. Read about the AI interview assistant.
Questions people ask
What is a monotonic stack?
A stack whose values stay in increasing or decreasing order from bottom to top. Before pushing a new value, you pop every element it breaks the order for, and each pop answers a question about the popped element.
When should you use a monotonic stack?
For next greater or next smaller element, how long until a higher value, spans of consecutive smaller values, and the largest rectangle under a bar chart.
Why is a monotonic stack O(n) with a nested loop?
Each index is pushed once and popped at most once, so the total work of all the inner while loops across the run is at most n pops.
Increasing or decreasing monotonic stack: which one?
Keep a decreasing stack to find the next greater element and an increasing stack to find the next smaller element. Store indexes so you can compute distances and widths.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
