Learn / Stacks and queues

Monotonic stack

Keep a stack whose values only increase (or only decrease) from bottom to top. When a new value breaks the order, pop. Each popped value has just met its next greater (or smaller) value. Every index is pushed and popped once, so the scan is O(n).

How to recognise it

  • For every element you need the next or previous greater or smaller element.
  • You must find how far each value stays the maximum or minimum: spans, ranges or rectangles.
  • A greedy choice is undone when a better value arrives: remove digits, collisions.

The picture

Think of people in a line looking right. Each one waits until someone taller arrives. The ones still waiting are in decreasing height from bottom to top: a taller one would already have answered the shorter ones before it.

answer = [-1] * n
stack = []                      # indexes still waiting
for i from 0 to n - 1:
    while stack and a[top] < a[i]:
        answer[pop] = a[i]      # a[i] is their next greater
    push i

Four variants

You wantPop while the top isDirection of scan
next greatersmaller than the new valueleft to right
next smallerbigger than the new valueleft to right
previous greaternot greater than the new valueleft to right, read the top after popping
previous smallernot smaller than the new valueleft to right, read the top after popping

You can also scan right to left and read the top after popping to get the "next" answers.

Contributions

When a value is popped, the new top is its nearest smaller (or greater) value on the left, and the current index is its nearest on the right. So the value is the minimum (or maximum) of left × right subarrays, and is the shortest bar of a rectangle that spans everything between. This one idea solves sum of subarray minimums, subarray ranges and the largest rectangle.

With equal values, use a strict comparison on one side and a non-strict one on the other, so that each subarray is counted once.

Common mistakes

  • Pushing values when you need widths: push indexes.
  • Forgetting to flush the stack at the end (a sentinel 0 or -∞ makes that automatic).
  • Counting equal values twice on both sides.

Problems

0 of 10 solved

Check yourself

For [2, 1, 5], what is the next greater element of 1?

Why is the monotonic-stack scan O(n) even with an inner while loop?

In Largest Rectangle in Histogram, when a bar is popped, how wide is its rectangle?

For the next greater element, should the stack keep values increasing or decreasing from bottom to top?