Skip to the content.

28. Monotonic Stack (Next Greater Element)

Back to the index

A stack kept in sorted order. Each new item pops every item it beats, and those pops are exactly the answers to ‘next greater’ or ‘next smaller’ questions, all in O(n).

How it works

Scan left to right and keep a stack of indices whose next greater element is still unknown. Their values are decreasing from bottom to top. When a new value x arrives, every stacked value smaller than x has just found its answer: pop it and record x. Then push the new index.

Each index is pushed once and popped at most once, so the whole scan is O(n), even though there is a loop inside a loop. The same idea answers daily temperatures, stock span, largest rectangle in a histogram and trapping rain water.

Diagram

flowchart TD
    A["Read next value x"] --> B{"Stack top value smaller than x?"}
    B -->|yes| C["Pop it: its answer is x"] --> B
    B -->|no| D["Push index of x"] --> A
    A -->|"input done"| E["Indices left on the stack get -1"]

Step-by-step trace

Input: Next greater element for [2, 1, 2, 4, 3].

i value Resolved (index gets value) Stack of values after result
0 2 none [2] [-1, -1, -1, -1, -1]
1 1 none [2, 1] [-1, -1, -1, -1, -1]
2 2 index 1 gets 2 [2, 2] [-1, 2, -1, -1, -1]
3 4 index 2 gets 4; index 0 gets 4 [4] [4, 2, 4, -1, -1]
4 3 none [4, 3] [4, 2, 4, -1, -1]

Result: Result: [4, 2, 4, -1, -1].

Complexity

Operation Time Space
Next greater / smaller for all items O(n) O(n)

Python reference implementation

def next_greater(nums):
    """For each item, the next item to its right that is larger, or -1."""
    result = [-1] * len(nums)
    stack = []                                  # indices, values decreasing
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            result[stack.pop()] = x             # x is the answer for that index
        stack.append(i)
    return result

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Prefix Sums (Subarray Sum Equals K) Next: KMP String Matching