Monotonic Stack
How a monotonic stack finds the next greater or smaller element in O(n), its variants, and the follow-up questions interviewers ask about it.
On this page
A monotonic stack is a stack whose items are kept in sorted order, either always decreasing or always increasing from bottom to top. It answers questions of the form "for each element, where is the nearest element on one side that is larger (or smaller)?" in one O(n) pass. You reach for it whenever each element needs to find the nearest element that beats it.
Suppose six buildings are 5, 3, 1, 4, 6 and 2 floors tall from west to east, and you want the first taller building to the east of each one. Walking east from every building takes O(n²) time in the worst case, because on a street where the buildings keep getting shorter every walk runs to the end. The stack does the same job in a single pass.
How the next-greater pass works
Walk through the buildings from west to east and keep a stack of the buildings that are still waiting for a taller one. For each new building, compare it with the building on top of the stack. While the new building is taller, it is the answer for the top building, so you pop that building and record the new building as its answer. When the top is not shorter, or the stack is empty, you push the new building so that it can wait for its own answer.
Every building shorter than the new one is popped before the push, so the heights on the stack always decrease from bottom to top. That ordering is what makes the stack monotonic. Popping is safe because the answer for a popped building is the first taller building to its right, and that is exactly the building that popped it, so the popped building is never needed again.
answer = [-1] * nfor i in 0 .. n - 1: while stack not empty and h[top] < h[i]: answer[pop()] = i push(i)return answer- heights051321344652stack (top on the right)answer0-11-12-13-14-15-1
1The answers start as -1, which means no taller building. The stack holds indexes, and each cell is written as index:height.
- heights05i1321344652stack (top on the right)00:5answer0-11-12-13-14-15-1
2Building 0 has 5 floors. The stack is empty, so nothing can be answered, and building 0 is pushed.
- heights0513i21344652stack (top on the right)00:511:3answer0-11-12-13-14-15-1
3Building 1 has 3 floors. The top has 5 floors and is not shorter, so building 1 is pushed.
- heights051321i344652stack (top on the right)00:511:322:1answer0-11-12-13-14-15-1
4Building 2 has 1 floor and is also pushed. The stack now holds heights 5, 3, 1, which decrease from bottom to top.
- heights05132134i4652stack (top on the right)00:511:3answer0-11-1233-14-15-1
5Building 3 has 4 floors, and the top (building 2) is shorter. Building 2 is popped, and its answer is 3.
- heights05132134i4652stack (top on the right)00:5answer0-113233-14-15-1
6Building 1 is also shorter than building 3, so it is popped as well, and its answer is 3.
- heights05132134i4652stack (top on the right)00:513:4answer0-113233-14-15-1
7The top now has 5 floors, which is taller than building 3, so popping stops and building 3 is pushed. The stack holds heights 5, 4.
- heights0513213446i52stack (top on the right)00:5answer0-11323344-15-1
8Building 4 has 6 floors. Building 3 is shorter, so it is popped, and its answer is 4.
- heights0513213446i52stack (top on the right)answer041323344-15-1
9Building 0 is shorter than building 4 as well, so it is popped, and its answer is 4.
- heights0513213446i52stack (top on the right)04:6answer041323344-15-1
10The stack is empty, so building 4 is pushed.
- heights051321344652istack (top on the right)04:615:2answer041323344-15-1
11Building 5 has 2 floors, which is shorter than the top, so it is pushed.
- heights051321344652stack (top on the right)04:615:2answer041323344-15-1
- pushes
- 6
- pops
- 4
12Buildings 4 and 5 are still on the stack, so they keep the answer -1. There were six pushes and four pops, because each building was pushed once and popped at most once.
Code
// For each building, the index of the first taller one to its right, or -1.
function nextTaller(heights) {
const answer = new Array(heights.length).fill(-1);
const stack = []; // indexes still waiting; heights decrease bottom to top
for (let i = 0; i < heights.length; i++) {
while (stack.length > 0 && heights[stack[stack.length - 1]] < heights[i]) {
answer[stack.pop()] = i; // i is the first taller one for the top
}
stack.push(i); // i waits for its own answer
}
return answer; // anything still waiting keeps -1
}
nextTaller([5, 3, 1, 4, 6, 2]); // [4, 3, 3, 4, -1, -1]# For each building, the index of the first taller one to its right, or -1.
def next_taller(heights):
answer = [-1] * len(heights)
stack = [] # indexes still waiting; heights decrease bottom to top
for i, h in enumerate(heights):
while stack and heights[stack[-1]] < h:
answer[stack.pop()] = i # i is the first taller one for the top
stack.append(i) # i waits for its own answer
return answer # anything still waiting keeps -1
next_taller([5, 3, 1, 4, 6, 2]) # [4, 3, 3, 4, -1, -1]The stack stores indexes instead of heights, because you need an index to write into answer, and an index also gives you the height and the distance i - index.
| Approach | Time | Space | Why |
|---|---|---|---|
| Walk right from every item | O(n²) | O(1) | On a street that keeps getting shorter, every walk goes to the end. |
| Monotonic stack | O(n) | O(n) | Each index is pushed once and popped at most once, so there are at most 2n stack operations. |
The while loop inside the for loop looks like it could make the algorithm O(n²). It does not, because every pop removes an index for good and only n indexes are ever pushed, so all the while loops together pop at most n times. This is the same argument of counting total moves that Two Pointers uses.
Variants
Next smaller instead of next greater
To find the next smaller element, reverse the comparison. You pop while the top is bigger than the new item, so the stack stays increasing from bottom to top, and each popped item gets the new item as its answer.
Previous greater and previous smaller
When the question asks about the nearest element on the left, the roles swap. You still pop while the top loses to the new item, but the answer belongs to the new item and is whatever remains on top of the stack after popping stops, or "none" if the stack is empty. You pop equal items as well, so that what remains is strictly greater (or strictly smaller).
| Question | Pop while the top is | Who receives the answer |
|---|---|---|
| Next greater | smaller than the new item | each popped item, whose answer is the new item |
| Next smaller | bigger than the new item | each popped item, whose answer is the new item |
| Previous greater | smaller than or equal to the new item | the new item, whose answer is the item left on top |
| Previous smaller | bigger than or equal to the new item | the new item, whose answer is the item left on top |
Circular arrays
If the array wraps around, so that the last element is followed by the first, an item near the end may have its answer near the start. The usual fix is to loop i from 0 to 2n - 1 and read the value at i % n. You push an index only during the first n iterations, and during the second pass you only pop. Each index is still pushed once, so the time stays O(n).
Largest rectangle under a bar chart
This problem uses an increasing stack. When a bar is popped because the new bar is lower, the popped bar can extend left as far as the item now on top of the stack and right as far as the new bar, so the widest rectangle of that height has a width equal to the number of bars strictly between those two positions. Taking the maximum over all popped bars gives the answer in O(n). A bar of height 0 added at the end forces every remaining bar to be popped.
Largest value in every sliding window, using a deque
A related problem asks for the largest value in every run of k neighbouring items. For [4, 2, 12, 3, 8, 7, 1] and k = 3 the answers are 12, 12, 12, 8, 8.
You keep a decreasing list of indexes as before. When a new item arrives, you remove from the back every item that is not bigger than it, because an item that is both older and smaller can never be the biggest of a window again. The biggest item of the current window is then at the front. Because the window slides, you also have to remove the front when its index falls out of the window. Removing from both ends needs a deque, and the JavaScript version below uses a head index instead of shift to avoid an O(n) removal.
function windowMax(nums, k) {
const dq = []; // indexes; values decrease from front to back
let head = 0; // front of the deque
const result = [];
for (let i = 0; i < nums.length; i++) {
if (head < dq.length && dq[head] <= i - k) head++; // front left the window
while (head < dq.length && nums[dq[dq.length - 1]] <= nums[i]) dq.pop();
dq.push(i);
if (i >= k - 1) result.push(nums[dq[head]]); // front is the biggest
}
return result;
}
windowMax([4, 2, 12, 3, 8, 7, 1], 3); // [12, 12, 12, 8, 8]from collections import deque
def window_max(nums, k):
dq = deque() # indexes; values decrease from front to back
result = []
for i, x in enumerate(nums):
if dq and dq[0] <= i - k:
dq.popleft() # front left the window
while dq and nums[dq[-1]] <= x:
dq.pop()
dq.append(i)
if i >= k - 1:
result.append(nums[dq[0]]) # front is the biggest
return result
window_max([4, 2, 12, 3, 8, 7, 1], 3) # [12, 12, 12, 8, 8]Each index enters the deque once and leaves at most once, so this takes O(n) time, compared with O(n·k) for scanning every window. The Sliding Window lesson covers windows whose size changes.
When a monotonic stack does not apply
The stack only works when each element needs the nearest element on one side that beats it. It does not help if you need the second greater element, or the greatest element within a range that is not a window of fixed size. The first needs an extra structure, such as a second stack, and the second is a range query that calls for a different structure such as a segment tree.
Pitfalls
In the interview
The signal in the problem statement is a question about the nearest element to the left or right of each item that is larger or smaller, a count of days or positions until something bigger or smaller appears, or a span of consecutive items that are not larger than the current one. Daily temperatures, stock spans, largest rectangle in a histogram, and the maximum of every window are the common forms. If a brute-force solution walks outward from each element, a monotonic stack is probably the intended improvement.
Questions to expect:
- "Why is this O(n) when there is a loop inside a loop?" Each index is pushed once and popped at most once, so the inner loop does at most n pops in total across the whole run. The work is n pushes plus at most n pops, which is at most 2n operations.
- "What happens with equal values?" It depends on the question. For "strictly greater" you pop only items that are strictly smaller, so equal items stay on the stack. For the previous-element variants you also pop equal items, so that the item left on top is strictly greater. Say which one you chose and why.
- "What if the array is circular?" Loop over the array twice, reading the element at
i % n, push indexes only in the first pass, and keep popping in the second. Items still waiting after two passes have no greater element at all. - "Can you do it from right to left instead?" Yes. Going right to left, the stack holds candidates for the answer instead of items waiting for one. For each item you pop candidates that are not larger, and the item left on top is its answer. Both directions are O(n).
- "How would you find the largest rectangle in a histogram?" Use an increasing stack of bar indexes. When a lower bar arrives, pop each taller bar and compute its rectangle, whose width runs from just after the new top of the stack to just before the lower bar. Keep the maximum.
- "How would you compute the number of days until a warmer day, or a stock span?" Both are the same pass. For days until a warmer day, store the index of the popped day and write
i - poppedinto its answer. For a stock span, run the previous-greater version and reporti - (index left on top), ori + 1when the stack is empty. - "What is the space complexity?" The stack takes O(n) space in the worst case, for example on a strictly decreasing array. The time is O(n), and the stack is the only extra structure besides the answer array.
- "Why does the sliding window maximum need a deque?" New items remove smaller items from the back, and items that slide out of the window must be removed from the front. A stack only supports one end, so it cannot remove items that have left the window.
Check yourself
Run the next-taller pass on [2, 7, 3, 5, 1]. What is the answer array?
The loop has a while inside a for. Why is the total time O(n) and not O(n²)?
You want the first shorter building to the right of each building. What changes in the code?
What to practise next
Run nextTaller by hand on [9, 7, 4, 2] and on [1, 3, 6, 8]. In one of them the stack only grows, and in the other it never holds more than one building. Then solve Waiting for a Bigger Wave and Freezer Warmest Stretch. The next lesson is Simple Sorts.