Monotonic Stack: Introduction
How a stack kept in sorted order finds the nearest bigger or smaller value for every element in one pass.
Picture a row of fence posts of different heights. From each post you want the first taller post to its right, and checking each post separately means walking the row again and again.
A monotonic stack answers the question for every post in a single walk. It is a stack, a pile you add to and take from only at the top, whose values are kept in sorted order. It fits any problem of the shape "for each element, find the nearest bigger (or smaller) element to its right (or left)".
The next greater element
Take the small array nums = [2, 1, 2, 4, 3]
In the picture, each bar is one value, with its position written under it as "index 0" to "index 4". An arrow leaves a bar and lands on the first bigger bar to its right. The 1 at index 1 only has to look one step: the 2 at index 2 is bigger, so its answer is 2.
Follow the orange arrow from index 0, labelled "index 0 waits past index 1 and index 2 until 4 arrives". The 2 there skips the 1 at index 1, which is smaller, and the 2 at index 2, which is only equal. It lands on the 4 at index 3, so the answer for index 0 is 4. The 4 and the 3 at the end have nothing bigger after them, and they get -1 as a "no answer" mark.
The "answer" label under each bar collects the results, which read [4, 2, 4, -1, -1]
Example 1
Output: [4, 2, 4, -1, -1]
Explanation: the 2 at index 0 waits until the 4. Nothing to the right of 4 or 3 is bigger.
Example 2
Output: [3, 4, 4, -1]
Scanning right from every element
What is the plain way to fill in the answer row? For each index, walk to the right one value at a time and stop at the first bigger one. That is two loops, one inside the other.
On our array that scanning compares six pairs of values in total. Now try an array that only goes down, such as [5, 4, 3, 2, 1]
The scans repeat each other's work. When index 0 scans right, it already walks past the 1 and the 2. Then index 1 and index 2 start their own scans over the same ground. The question is how to read the array once and still give every index its answer.
Keeping the waiting values on a stack
Turn the question around. Read the array from left to right and keep a pile of the indices whose answer is not known yet. When a new value arrives, it is the answer for every waiting value that is smaller than it.
The picture has one column per step, headed i = 0i = 4
- At
the 2 arrives. Nothing is waiting, so the 2 starts the pile.i = 0 - At
the 1 is not bigger than the 2 on top, so it cannot answer anything. It goes on top and waits too.i = 1 - At
the new 2 is bigger than the 1 on top. The orange box "pop: index 1 gets 2" shows that 1 leaving the pile with its answer. The next value down is the 2 from index 0, which is equal and not smaller, so the new 2 stops there and goes on top.i = 2 - At
the 4 is bigger than both 2s. It removes them one after the other, and both index 2 and index 0 get 4. The pile is now just the 4.i = 3 - At
the 3 is smaller than the 4, so it waits on top.i = 4
When the array ends, index 3 and index 4 are still in the pile. Nobody answered them, so they keep -1.
Why does the new value only ever look at the top of the pile? Look down any column: from the bottom up, the values never get bigger. A value goes on the pile only after every smaller value has been popped from the top, so it always sits on something at least as big. If the top is not smaller than the new value, nothing further down is smaller either, and the new value can stop.
Adding to the top of the stack is called a push, and removing from the top is a pop. "Monotonic" means "only going one way". Our stack is monotonic because its values only go down from bottom to top (the two 2s at i = 2
How much work the pass does
One new value can pop several waiting values, as the 4 does at i = 3
A comparison that finds the top bigger or equal stops the popping, once per new value at most. On [5, 4, 3, 2, 1]
The Java template
Should the stack hold the values or their indices? Indices. An index gives the value through nums[index]
The method nextGreater
- First it creates the result array
and fills it with -1 usinganswer , so every index that is never popped already holds its "no answer" mark.Arrays.fill - Then it creates
, anstack that holds the waiting indices, the pile from the second picture. ItsArrayDeque<Integer> ,push andpop all act on the same end, so that end is the top box of each column.peek - A
loop reads each indexfor from left to right.i - Inside it, a
loop pops the top index as long as the stack is not empty and the value at the top is smaller thanwhile . Each popped index getsnums[i] as its answer.nums[i] - After the popping,
is pushed, where it waits for its own answer.i
A second method, stepsToGreaterwaitingi - waitingmain
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class NextGreaterElement {
// For every index, the first value to its right that is strictly bigger, or -1.
static int[] nextGreater(int[] nums) {
int[] answer = new int[nums.length];
Arrays.fill(answer, -1); // indices never popped keep -1
Deque<Integer> stack = new ArrayDeque<>(); // indices still waiting for an answer
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
answer[stack.pop()] = nums[i]; // nums[i] is the first bigger value
}
stack.push(i); // i now waits for its own answer
}
return answer;
}
// Same pass, but the answer is how many steps to the right the bigger value is, or 0.
static int[] stepsToGreater(int[] nums) {
int[] steps = new int[nums.length];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
int waiting = stack.pop();
steps[waiting] = i - waiting;
}
stack.push(i);
}
return steps;
}
public static void main(String[] args) {
int[][] inputs = {{2, 1, 2, 4, 3}, {1, 3, 2, 4}, {5, 4, 3}, {2, 2}, {7}, {}};
for (int[] nums : inputs) {
System.out.println(Arrays.toString(nums) + " -> next greater "
+ Arrays.toString(nextGreater(nums)));
}
int[] nums = {2, 1, 2, 4, 3};
System.out.println(Arrays.toString(nums) + " -> steps to greater "
+ Arrays.toString(stepsToGreater(nums)));
}
}
Running it prints:
[2, 1, 2, 4, 3] -> next greater [4, 2, 4, -1, -1]
[1, 3, 2, 4] -> next greater [3, 4, 4, -1]
[5, 4, 3] -> next greater [-1, -1, -1]
[2, 2] -> next greater [-1, -1]
[7] -> next greater [-1]
[] -> next greater []
[2, 1, 2, 4, 3] -> steps to greater [3, 1, 1, 0, 0]
The first two lines, for Example 1 and Example 2, give [4, 2, 4, -1, -1][3, 4, 4, -1][5, 4, 3]Arrays.fill[2, 2][-1, -1]
Look at the last line, [3, 1, 1, 0, 0]
Cost of the template
- Time: O(n), because each of the n indices is pushed once and popped at most once, and each run of the
loop ends with at most one comparison that does not pop.while - Space: O(n), because on a falling array such as
no index is ever popped, so all of them are still on the stack at the end.[5, 4, 3]
Next smaller, previous greater, previous smaller
The same stack answers three more questions about each element. You choose the side to look at (right or left) and what you look for (bigger or smaller), which gives four combinations in all.
Next smaller: flip the comparison
To find the first smaller value to the right, pop while the top is bigger than the new value. The stack now goes up from bottom to top instead of down. On our array, the 2 at index 0 is answered at once by the 1 after it, and the 4 at index 3 is answered by the 3.
Previous greater and previous smaller: read the top that remains
Looking to the left changes when an answer becomes known. A value's left side is complete the moment it arrives, so its answer is ready right away. Pop every index that cannot be the answer, and whatever is left on top is the nearest one that can.
The arrows in this picture point left, to the previous smaller value. Follow the orange one: "3 at index 4 looks back past 4 and finds 2". When the 3 arrives, the stack holds the indices of the values 1, 2 and 4, with the 4 on top. The 4 is not smaller than 3, so it is popped. The top that remains is the 2 at index 2, and that is the answer.
Popping the 4 loses nothing. Any later value that the 4 could answer as "previous smaller" must be bigger than 4. Such a value is also bigger than 3, and the 3 is closer, so the 3 answers it first.
For "previous smaller", an equal value must be popped as well, because it is not smaller. That is why the previous-smaller pass pops while the top is >=<=[2, 1, 2, 4, 3]
| Question | Pop while the top is | Answer comes from | Result |
|---|---|---|---|
| Next greater | smaller than the new value | the new value, for each popped index | [4, 2, 4, -1, -1] |
| Next smaller | bigger than the new value | the new value, for each popped index | [1, -1, -1, 3, -1] |
| Previous greater | smaller than or equal to the new value | the top that remains | [-1, 2, -1, -1, 4] |
| Previous smaller | bigger than or equal to the new value | the top that remains | [-1, -1, 1, 2, 2] |
This program runs the three new variants on the running example.
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class MonotonicVariants {
// Right side: pop while the top loses to nums[i]; nums[i] answers each popped index.
static int[] nextSmaller(int[] nums) {
int[] answer = new int[nums.length];
Arrays.fill(answer, -1);
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) {
answer[stack.pop()] = nums[i];
}
stack.push(i);
}
return answer;
}
// Left side: pop everything that cannot answer i; the top that remains is the answer.
static int[] previousGreater(int[] nums) {
int[] answer = new int[nums.length];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[stack.peek()] <= nums[i]) {
stack.pop();
}
answer[i] = stack.isEmpty() ? -1 : nums[stack.peek()];
stack.push(i);
}
return answer;
}
static int[] previousSmaller(int[] nums) {
int[] answer = new int[nums.length];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < nums.length; i++) {
while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) {
stack.pop();
}
answer[i] = stack.isEmpty() ? -1 : nums[stack.peek()];
stack.push(i);
}
return answer;
}
public static void main(String[] args) {
int[] nums = {2, 1, 2, 4, 3};
System.out.println("nums " + Arrays.toString(nums));
System.out.println("next smaller " + Arrays.toString(nextSmaller(nums)));
System.out.println("previous greater " + Arrays.toString(previousGreater(nums)));
System.out.println("previous smaller " + Arrays.toString(previousSmaller(nums)));
}
}
Running it prints:
nums [2, 1, 2, 4, 3]
next smaller [1, -1, -1, 3, -1]
previous greater [-1, 2, -1, -1, 4]
previous smaller [-1, -1, 1, 2, 2]
The last line, [-1, -1, 1, 2, 2]<=
Spotting a monotonic stack problem
How do you know a problem wants this stack? Look for these signs:
- For each element you need the nearest element on one side that is bigger or smaller. "How many days until a warmer day" is next greater, measured in steps like
.stepsToGreater - An element stays relevant only until something bigger (or smaller) arrives and blocks it. The 1 at index 1 in our array stops mattering once the 2 after it shows up.
- You need how far an element can stretch. In our array, the 2 at index 2 can stretch left until it meets the previous smaller value, the 1 at index 1.
Traps
Three small changes to nextGreater[2, 1, 2, 4, 3][4, 2, 4, -1, -1]
- No fill: the
line is removed.Arrays.fill(answer, -1) - Pop on equal: the
condition useswhile instead of<= .< - No empty check: the
part of the condition is removed.!stack.isEmpty() &&
Running the three versions prints:
no fill: [4, 2, 4, 0, 0]
pop on equal: [2, 2, 4, -1, -1]
no empty check: NullPointerException
The first line ends in 0, 0int
The second line starts with 2 instead of 4. With <=
The last line is a NullPointerExceptioni = 0peekArrayDequenullnullintnull
Where to go next
These problems wait for a bigger value to the right and answer on the pop.
Daily Temperatures counts the days until a warmer one, the same pass as .stepsToGreaterNext Greater Element II lets the search wrap around from the end of the array back to the start.
These look for a bigger value to the left.
Online Stock Span measures how far back the previous higher price is, as prices arrive one at a time. Each stack entry keeps a price and its span, so the days of a popped entry are counted in one step.132 Pattern looks for three values in a low, high, middle order. It reads the array from the right, so a value is popped when a bigger value to its left arrives, and each popped value becomes a candidate for the middle one.
These need the borders on both sides.
Largest Rectangle in Histogram uses the previous and next smaller bar to see how wide each bar can stretch.Sum of Subarray Minimums finds the nearest smaller value on each side of every value, with one walk from each end, to count how many subarrays have it as their smallest value.Trapping Rain Water uses two markers that move inward. It also shows a stack version, where each taller bar that arrives fills water above the bar it pops.
This one keeps a stack whose digits never go down, as long as removals are left.
Remove K Digits removes a given number of digits to leave the smallest number, popping a bigger digit when a smaller one follows it.