Monotonic Stacks
A monotonic stack is an ordinary stack that never holds values out of order. Before each push it pops everything that would break the order, and each popped value leaves with its answer known. That one rule turns a family of O(n²) scanning problems into a single O(n) pass.
A Stack That Refuses Disorder
A monotonic stack is an ordinary stack with one extra rule on every push: first pop everything that would break the order. Its contents therefore stay sorted at all times, either increasing or decreasing from bottom to top.
The rule looks like a restriction but works as a filter. Each pop throws away an item that has just been shown to be useless, and the moment it is thrown away is exactly the moment its answer is known.
The problems it solves are the next greater element family: for each item in an array, find the nearest item to its right that is larger. Scanning forward from every position is O(n²). A monotonic stack does it in O(n).
Why this works: when scanning left to right, a new value makes every earlier, smaller value useless as an answer for anything further right. Any later position looking for a bigger value would find the new one first, since it is both larger and closer. So those smaller earlier values can be dropped for good, and the new value is their answer.
Direction decides the order. For next greater, keep a decreasing monotonic stack: smaller items are popped when a bigger one arrives, and the bigger one is their answer. For next smaller, keep an increasing monotonic stack. The pairing is easy to get backwards; work it out from what gets popped rather than memorising it.
- Previous greater or previous smaller: the same stack, read at push time; after the pops, the new top is the answer for the item being pushed
- Next smaller element uses the increasing stack: next smaller element
- If the array is already sorted the right way, nothing is ever popped and the stack ends up holding all n items
The Pop Is the Answer
This is the idea to remember, and the reason the technique is more than a stack that happens to be sorted.
The monotonic stack algorithm for next greater element: scan left to right, keeping a stack of indices whose values decrease from bottom to top. At each index i, while the stack is not empty and the value at the top is less than the value at i, pop that index and record that its next greater element is the value at i. Then push i.
The popped item's answer is the current one because the current item is the first value that beats it. Everything between them was smaller, or it would have popped the item earlier. That first is what makes it the next greater element, not just a greater one.
Store indices, not values. The value is always arr[stack.top()], but an index cannot be recovered from a value, and many problems need the distance. Daily temperatures asks how many days until a warmer day, which is i - poppedIndex; with values on the stack, that answer is gone.
Whether to pop on < or <= depends on duplicates. With strict <, equal items do not pop each other, so the answer is the next strictly greater item. With <=, equal items pop, and the answer becomes the next greater or equal. Read the problem and choose on purpose; the tracer below shows the wrong choice on [72, 72, 75].
The scan can also run right to left. Then the stack holds candidate answers instead of waiting questions: pop everything not greater than the current value, and whatever is left on top is its answer. Both directions are O(n).
- Practice the basic form: next greater element, daily temperatures
- Stock span is the previous-greater version: online stock span
- Popping on equal values is right when the problem says "greater or equal", wrong when it says "greater"
Why It Is Linear
The code has a while loop inside a for loop, which looks quadratic. It is not, and explaining why is the difference between understanding the technique and memorising it.
The argument is amortised. Each index is pushed exactly once, in its own iteration. Each index is popped at most once, and is never looked at again after that. So the total number of pops over the whole run is at most n, not n per iteration.
One iteration can pop many items, but only items pushed by earlier iterations, and each of those can be popped only once. The inner loop's total work over the whole run is therefore O(n).
Total: O(n) time and O(n) space. The space is the stack, which holds all n items in the worst case, a strictly decreasing input where nothing is ever popped.
The same push-once, pop-once count makes the sliding window and the monotonic queue linear. Whenever each item enters and leaves a structure at most once, nested loops do not mean quadratic time.
The leftovers matter. When the scan ends, whatever is still on the stack was never popped, so no answer exists for it: nothing larger came to its right. It needs an explicit default, usually −1 or 0. The last item is always a leftover, so this case occurs on every input; the bug just hides when the result array starts out filled with the right default, as 0 does for daily temperatures.
For a circular array, where the search wraps around to the start, loop 2n times using i % n as the index and push only during the first pass. Every item then sees a full circle of candidates without copying the array. Practice it in next greater element II.
- Worst-case stack size is n, on input that is already in the stack's order
- Initialise the result with the "no answer" value before the loop, so leftovers need no second pass
- In the circular version, pushing during the second pass would count items twice
Terms, operations, and practical uses
Invariants
- Monotonic IncreasingValues increase from bottom to top. Used for next smaller and previous smaller questions.
- Monotonic DecreasingValues decrease from bottom to top. Used for next greater and previous greater questions.
- Conflict ResolutionPopping items from the top until the new item can be pushed without breaking the order.
Mechanics
- Index StoragePushing the array index rather than the value, so distances and widths can be computed when an item is popped.
- The PopperThe new item that forces others off the stack. It is the next greater (or next smaller) item for each one it pops.
- O(N) ComplexityA while loop inside a for loop, but O(n) overall: every index is pushed once and popped at most once.
Classic problems
- Next Greater ElementThe first item to the right that is larger than the current one; daily temperatures asks for the distance to it.
- Largest Rectangle in HistogramEach bar's rectangle is bounded by its previous and next smaller bars, found with an increasing stack in O(n).
- Stock SpannerHow many consecutive days up to today had a price less than or equal to today's: a previous-greater search.
Code in Python, C++ and Java
def dailyTemperatures(temps):
ans = [0] * len(temps)
stack = [] # Stores indices, monotonically decreasing by temp
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
prev_index = stack.pop()
ans[prev_index] = i - prev_index
stack.append(i)
return ans
print('Wait days:', dailyTemperatures([73, 74, 75, 71, 69, 72]))#include <iostream>
#include <vector>
#include <stack>
using namespace std;
vector<int> dailyTemperatures(vector<int>& temps) {
vector<int> ans(temps.size(), 0);
stack<int> st; // Stores indices
for (int i = 0; i < temps.size(); i++) {
while (!st.empty() && temps[st.top()] < temps[i]) {
int prev_index = st.top();
st.pop();
ans[prev_index] = i - prev_index;
}
st.push(i);
}
return ans;
}
int main() {
vector<int> temps = {73, 74, 75, 71, 69, 72};
vector<int> ans = dailyTemperatures(temps);
cout << "Wait days: [";
for (size_t i = 0; i < ans.size(); i++) { if (i) cout << ", "; cout << ans[i]; }
cout << "]\n";
}import java.util.*;
class Main {
public int[] dailyTemperatures(int[] temps) {
int[] ans = new int[temps.length];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < temps.length; i++) {
while (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
int prevIndex = stack.pop();
ans[prevIndex] = i - prevIndex;
}
stack.push(i);
}
return ans;
}
public static void main(String[] args) {
int[] ans = new Main().dailyTemperatures(new int[]{73, 74, 75, 71, 69, 72});
System.out.println("Wait days: " + Arrays.toString(ans));
}
}Step through it
Running on temps = [73, 74, 75, 71, 69, 72], then [72, 72, 75]
Largest Rectangle in a Histogram
Most monotonic stack problems are a next greater or next smaller search in disguise. The hardest standard one shows the technique doing something a simple scan cannot.
Given bar heights, find the largest rectangle that fits inside the histogram. A rectangle is fixed by choosing one bar as its height and stretching left and right while the bars stay at least that tall. So for every bar the question is: how far can it stretch before it hits a shorter bar on each side?
Those limits are the previous smaller and next smaller items, both monotonic stack questions. With an increasing stack of indices, when a bar shorter than the top arrives, the popped bar's right limit is the current index and its left limit is whatever now sits below it on the stack. The width is the gap between those two limits, not counting either.
The width is where code goes wrong. After popping index top, the width is i - stack.top() - 1, using the new top after the pop, not the popped index. If the stack is empty after the pop, the bar reaches the left edge and the width is simply i.
For heights [2, 1, 5, 6, 2, 3] the answer is 10: bars 5 and 6 together, height 5, width 2. It is found when the 2 at index 4 pops index 2 (height 5): the new top is index 1, so the width is 4 − 1 − 1 = 2.
A clean trick: append a sentinel bar of height 0. It is shorter than everything, so it forces every remaining bar off the stack inside the normal loop, and no separate leftover pass is needed.
The result is O(n) for a problem whose brute force is O(n²). The same shape solves maximal rectangle in a binary matrix: treat each row as the base of a histogram whose heights count the consecutive 1s above, and run the histogram algorithm per row, O(rows × cols) overall. Trapping rain water can also be solved with a monotonic stack, though two pointers are simpler there.
- Practice: largest rectangle in histogram, maximal rectangle, trapping rain water
- Asteroid collision uses the same pop-while-the-top-loses loop: asteroid collision
- When the minimum of a window, not of everything to the right, is needed, switch to a monotonic queue