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]. Each value plays the part of one post, and the question for each one is: what is the first value to its right that is strictly bigger?

Bars for nums = [2, 1, 2, 4, 3]. Arrows point to each value's next greater value: index 0 to 4, index 1 to 2, index 2 to 4. Indices 3 and 4 get -1. The arrow from index 0 is highlighted.

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] from left to right. The value an arrow lands on is called the next greater element of the value it leaves.

Example 1
Input: nums = [2, 1, 2, 4, 3]
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
Input: nums = [1, 3, 2, 4]
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]. No scan ever finds a bigger value, so every scan runs to the end of the array: 4 + 3 + 2 + 1 = 10 comparisons. With n values going down it is n(n - 1) / 2 comparisons, which grows like n2.

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 stack of values while reading nums = [2, 1, 2, 4, 3]. At i = 2 index 1 is popped and gets 2. At i = 3 index 2 and index 0 are popped and get 4. The stack ends as 4, 3.

The picture has one column per step, headed i = 0 to i = 4, where i is the index being read. The pile sits on the line, with its top as the highest box, and teal marks the value just added. The boxes show values to keep the picture readable, while the pile itself keeps their indices.

  • At i = 0 the 2 arrives. Nothing is waiting, so the 2 starts the pile.
  • At i = 1 the 1 is not bigger than the 2 on top, so it cannot answer anything. It goes on top and waits too.
  • At i = 2 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.
  • At i = 3 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.
  • At i = 4 the 3 is smaller than the 4, so it waits on top.

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 show that equal neighbours are allowed here).

How much work the pass does

One new value can pop several waiting values, as the 4 does at i = 3. Is this still two nested loops in disguise? No. Each index is pushed once and popped at most once, so over the whole array there are at most n pops. In our run there were 5 pushes and 3 pops.

A comparison that finds the top bigger or equal stops the popping, once per new value at most. On [5, 4, 3, 2, 1], where scanning needed 10 comparisons, the stack needs 4: each value after the first glances at the top once and is pushed.

The Java template

Should the stack hold the values or their indices? Indices. An index gives the value through nums[index], and it also says which answer slot to fill and how far away the answer is.

The method nextGreater works like this:

  1. First it creates the result array answer and fills it with -1 using Arrays.fill, so every index that is never popped already holds its "no answer" mark.
  2. Then it creates stack, an ArrayDeque<Integer> that holds the waiting indices, the pile from the second picture. Its push, pop and peek all act on the same end, so that end is the top box of each column.
  3. A for loop reads each index i from left to right.
  4. Inside it, a while loop pops the top index as long as the stack is not empty and the value at the top is smaller than nums[i]. Each popped index gets nums[i] as its answer.
  5. After the popping, i is pushed, where it waits for its own answer.

A second method, stepsToGreater, runs the same pass but stores how many steps to the right the bigger value is. For a popped index named waiting that is i - waiting, and an index with no bigger value keeps 0. The main method runs both examples, a falling array, two equal values, a single value and an empty array, then the step counts for the running example.

Java
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:

Output
[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] and [3, 4, 4, -1], as expected. On [5, 4, 3] nothing is ever popped, so every slot keeps the -1 from Arrays.fill. The line for [2, 2] gives [-1, -1], because the second 2 is equal to the first and the pop needs strictly smaller. The single value and the empty array run without errors.

Look at the last line, [3, 1, 1, 0, 0]. The 2 at index 0 is popped at index 3, three steps later, which is the long orange arrow in the first picture.

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 while loop ends with at most one comparison that does not pop.
  • Space: O(n), because on a falling array such as [5, 4, 3] no index is ever popped, so all of them are still on the stack at the end.

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.

Bars for nums = [2, 1, 2, 4, 3]. Arrows point left to each value's previous smaller value: index 2 to 1, index 3 to 2, index 4 to 2. Indices 0 and 1 get -1. The arrow from index 4 is highlighted.

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 >= the new value, and the previous-greater pass pops while it is <=. The four variants side by side, with their results on [2, 1, 2, 4, 3]:

QuestionPop while the top isAnswer comes fromResult
Next greatersmaller than the new valuethe new value, for each popped index[4, 2, 4, -1, -1]
Next smallerbigger than the new valuethe new value, for each popped index[1, -1, -1, 3, -1]
Previous greatersmaller than or equal to the new valuethe top that remains[-1, 2, -1, -1, 4]
Previous smallerbigger than or equal to the new valuethe top that remains[-1, -1, 1, 2, 2]

This program runs the three new variants on the running example.

Java
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:

Output
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], is the answer row in the second bar picture. On the "previous greater" line, the 3 at index 4 gets 4, the value it had to pop in the previous-smaller pass. The 2 at index 2 gets -1 there, because the 2 at index 0 is only equal and is popped by the <=.

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 break it in ways that are easy to miss. Each change was run on [2, 1, 2, 4, 3], whose correct answer is [4, 2, 4, -1, -1]:

  • No fill: the Arrays.fill(answer, -1) line is removed.
  • Pop on equal: the while condition uses <= instead of <.
  • No empty check: the !stack.isEmpty() && part of the condition is removed.

Running the three versions prints:

Output
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, 0. A new Java int array starts with every slot at 0, so the 4 and the 3 report 0 as if 0 were a bigger value to their right. With the fill missing, the "no answer" mark is gone.

The second line starts with 2 instead of 4. With <=, the 2 at index 2 pops the equal 2 at index 0, so the method answers "next greater or equal" instead. That is the right choice when a problem asks for "at least as big"; read the wording and pick the comparison on purpose.

The last line is a NullPointerException. At i = 0 the stack is empty, and peek on an empty ArrayDeque returns null. Using that null as an array index needs an int, and turning null into one throws.

Where to go next

These problems wait for a bigger value to the right and answer on the pop.

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.