awelgorithms

// learn

The monotonic stack

A monotonic stack is a stack kept in sorted order, always increasing or always decreasing from bottom to top. Before pushing a new value you pop everything that would break the order, and that pop is where the answers come from.

Updated

When a value is popped because a bigger one arrived, the bigger one is its next greater element. So one left-to-right pass answers "how far to the next warmer day" or "next greater element" for every position at once, in O(n) instead of the O(n²) of checking every later item.

When to use it

The template

def next_greater(nums):
    answer = [-1] * len(nums)       # -1 when nothing greater follows
    stack = []                      # indexes still waiting
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            answer[stack.pop()] = x # x is their next greater
        stack.append(i)             # values on the stack only decrease
    return answer

The variants you will meet

Next greater and next smaller

Pop while the top is smaller than the new value to find next greater elements; pop while it is larger for next smaller. Scanning right to left, or reading the stack top before pushing, gives the nearest one on the left instead.

Spans and distances

Store indexes instead of values and the distance falls out: Daily Temperatures is next greater with i - j as the answer. Largest Rectangle in a Histogram uses the nearest smaller bar on each side to find how wide each bar can stretch.

Time and space complexity

O(n) time even with the inner while loop: each index is pushed once and popped at most once, so there are at most 2n stack operations in total. Space is O(n) for the stack in the worst case, a strictly decreasing input.

check which skills you have 10 minutes, free, no account.

All 6 lessons, in order

Common questions

Increasing or decreasing monotonic stack: which do I need?

For the next greater element, keep a decreasing stack: a bigger value pops the smaller ones waiting below it. For the next smaller element, keep an increasing stack. The value that does the popping is the answer for each value it pops.

Why is a monotonic stack O(n) with a nested loop?

The inner loop only pops, and each index can be popped once after being pushed once. Over the whole scan that is at most n pops, so the total work is O(n) no matter how the pops are spread out.

Should I push values or indexes?

Indexes, almost always. You can still read the value as nums[i], and the index gives you distances (Daily Temperatures) and widths (largest rectangle) that values alone can't.

Monotonic stack or monotonic queue?

A monotonic stack answers nearest-greater or nearest-smaller questions. A monotonic queue (a deque) answers the maximum or minimum of a sliding window, because it can also drop items that fall out of the window from the front.

Other guides