Stacks and heaps · Intermediate

Monotonic stack

Keep a stack whose values only increase (or only decrease); each new element pops everything it beats, answering "next greater" for all of them at once.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

For each element you want the nearest element to its right (or left) that is larger, or smaller. Scanning right from every element is quadratic. Instead, keep the indices still waiting for an answer on a stack. Their values are decreasing from bottom to top, because a larger value would already have answered the smaller ones below it.

When a new value arrives, it is the answer for every waiting index whose value is smaller, and those are exactly the ones on top. Pop them, record the answer, then push the new index. The monotonic deque is the same idea with removals from the front, used for sliding-window maximums.

How to recognise it

  • "Next greater", "next smaller", "previous warmer day", "how many days until"…
  • For each element, the answer is the nearest element in one direction that beats it.
  • Spans, visible buildings, histogram areas: anything bounded by the first larger or smaller neighbour.

When not to use it

  • You need the k-th greater element or a global order statistic: a heap or sorting fits better.
  • The comparison is not a total order on single values (for example two-dimensional dominance).

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

# For each i, distance to the next strictly greater value (0 if none)
answer = [0] * n
stack = []                       # indices; values decrease from bottom to top
for i in range(n):
    while stack and a[stack.top()] < a[i]:
        j = stack.pop()
        answer[j] = i - j        # a[i] is the first greater value after j
    stack.push(i)
return answer                    # indices left on the stack have no greater value
  • Store indices, not values: you usually need the distance or position.
  • Strict versus non-strict comparison decides how equal values are treated; pick it from the problem statement.

Complexity

Time O(n), extra space O(n). Each index is pushed once and popped at most once, so the inner while loop runs at most n times over the whole scan.

Worked examples

Temperatures [30, 28, 31, 29, 33]

Push 0 (30), push 1 (28). 31 arrives: pops 1 (answer 1) and 0 (answer 2), then push 2. Push 3 (29). 33 arrives: pops 3 (answer 1) and 2 (answer 2). Index 4 never finds a warmer day: answer 0.

Pitfalls

  • Comparing with the wrong sign and building an increasing stack when you needed a decreasing one.
  • Forgetting the elements left on the stack at the end (they need a default answer).

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.monotonic-stack · version 1