Advanced 12 min

Monotonic stacks

A monotonic stack keeps its pending values in order so later values can resolve several at once.

How it works

Place each index on the stack while its answer is unknown. Arriving value 4 is greater than both 1 and 2, so it resolves and removes both indexes. It then becomes a pending value itself. Every index goes on once and comes off at most once, giving O(n) total work.

Walk through an example

For the next greater element, store indexes that have not found an answer. As each larger value arrives, pop and answer every smaller top value before pushing the new index.

What to watch for

Use a strict comparison for strictly greater. Equal values should stay pending until a larger value arrives.

Code example

def next_greater(a):
    answers = [None] * len(a)
    pending = []
    for i, value in enumerate(a):
        while pending and a[pending[-1]] < value:
            answers[pending.pop()] = value
        pending.append(i)
    return answers

Check your understanding

What is the next greater value for 1?

See the example and explanation
Worked example
Given [2, 1, 4, 3]
Answer 4

The next position after 1 contains 4, and 4 is larger. It answers both 1 and the earlier 2.

Open practice problem