Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Monotonic Stacks & Queues

Next greater elements, sliding-window maxima and the largest rectangle, in linear time.

For each day of the year, how many days until a warmer one? Checking every later day costs O(n2)O(n^2). A stack that keeps only the days still waiting for their answer finds all of them in one pass, and the same idea finds sliding-window maxima, the water trapped between bars and the largest rectangle under a histogram, each in O(n)O(n).

What you’ll learn

  • Compute the next (or previous) greater or smaller element of every index in O(n)O(n) with a monotonic stack, and prove the bound by counting pushes and pops.
  • Choose strict or non-strict comparisons when values repeat, and adapt the loop to previous elements and circular arrays.
  • Solve spans, waiting times, trapped rain water, histogram rectangles and the sum of subarray minimums with nearest greater or smaller boundaries.
  • Maintain sliding-window maxima with a monotonic deque in O(n)O(n) total time, and prove its invariant.
  • Recognize "nearest greater or smaller" and "window maximum or minimum" structure in a problem statement.

Next greater element: from O(n²) to O(n)

For each index ii of an array a[0..n−1]a[0..n-1], the next greater element is at the smallest j>ij > i with a[j]>a[i]a[j] > a[i], or nowhere (−1-1). The brute force scans right from each ii: O(n2)O(n^2) in the worst case, for instance on a decreasing array, where every scan runs to the end.

The waste is in rescanning elements that can no longer be anyone's answer. Scan left to right instead, and keep a stack of the indices still waiting for their answer. Their values never increase from bottom to top: if a waiting element were smaller than a later waiting one, the later one would already have answered it. When a[i]a[i] arrives it is the answer for every waiting index with a smaller value, and those are exactly the ones on top. Pop them, record ii for each, then push ii.

python
def next_greater(a):
    n = len(a)
    ans = [-1] * n               # -1: no greater element to the right
    stack = []                   # indices still waiting; values never increase upward
    for i, x in enumerate(a):
        while stack and a[stack[-1]] < x:
            ans[stack.pop()] = i # x is the first greater element after it
        stack.append(i)
    return ans

A monotonic stack: from bottom to top its values never increase. A popped index's answer is the index that popped it; the indices still on the stack at the end have no greater element to their right.

Predict before you look

On the array [6,2,5,4,3,8,7,1,4][6, 2, 5, 4, 3, 8, 7, 1, 4], how many pops does next_greater perform in total?

Show the answer

6 pops

Each index is popped at most once, when its next greater element arrives: 5 pops the 2; 8 pops 3, 4, 5 and 6; the final 4 pops the 1. That makes 6. The indices of 8, 7 and the final 4 stay on the stack, because nothing greater follows them: 9−3=69 - 3 = 6.

Why it is linear, and why it is right

DerivationProof
  1. stack={ j<i  :  a[j]≥a[k] for all j<k<i }\text{stack} = \{\, j < i \;:\; a[j] \ge a[k] \text{ for all } j < k < i \,\}

    Invariant. Before index ii is processed, the stack holds exactly the indices j<ij < i with no greater element among a[j+1..i−1]a[j+1..i-1], in increasing order of index; their values never increase from bottom to top.

  2. nge⁡(j)=i\operatorname{nge}(j) = i

    Pops are correct. If jj is popped at step ii, then a[j]<a[i]a[j] < a[i], while a[j]≥a[k]a[j] \ge a[k] for every kk between them by the invariant. So ii is the first greater element after jj.

  3. a[top] ≥ a[i]whenever i is pushed onto a nonempty stacka[\text{top}] \ \ge\ a[i] \quad \text{whenever } i \text{ is pushed onto a nonempty stack}

    The invariant survives. Popping stops at the first index jj with a[j]≥a[i]a[j] \ge a[i], and everything below it is at least as large, so the indices that remain are exactly those still waiting after a[i]a[i]. Pushing ii keeps the values non-increasing.

  4. #pops ≤ #pushes−1=n−1⟹T(n)=Θ(n)\#\text{pops} \ \le\ \#\text{pushes} - 1 = n - 1 \quad\Longrightarrow\quad T(n) = \Theta(n)

    Linear time, by the aggregate method. Each index is pushed once and popped at most once, and the last index pushed is never popped, so the inner loop runs at most n−1n - 1 times over the whole run:

For each ii, find …Pop whileAnswer
the next greater elementa[top]<a[i]a[\text{top}] < a[i]each popped index gets ii
the next greater-or-equal elementa[top]≤a[i]a[\text{top}] \le a[i]each popped index gets ii
the next smaller elementa[top]>a[i]a[\text{top}] > a[i]each popped index gets ii
the previous greater elementa[top]≤a[i]a[\text{top}] \le a[i]ii gets the top left after popping
the previous smaller elementa[top]≥a[i]a[\text{top}] \ge a[i]ii gets the top left after popping
the next greater element, circularlya[top]<a[i mod n]a[\text{top}] < a[i \bmod n], for i=0,…,2n−1i = 0, \dots, 2n - 1each popped index gets i mod ni \bmod n; push only while i<ni < n
All scans run left to right. Flip the comparison to switch between greater and smaller. Whether equal values count as answers depends on the strictness of the pop condition, and the two directions treat ties oppositely: popping while a[top]≤a[i]a[\text{top}] \le a[i] gives each popped index its next greater-or-equal element, but gives ii its previous strictly greater one. When in doubt, test on an array with repeats.
Check your understanding

Scanning left to right, which loop gives each ii its nearest index to the left holding a value less than or equal to a[i]a[i]?

  1. Pop while a[top]≥a[i]a[\text{top}] \ge a[i]; then the top, if any, is ii's answer
  2. Pop while a[top]>a[i]a[\text{top}] > a[i]; then the top, if any, is ii's answer
  3. Pop while a[top]<a[i]a[\text{top}] < a[i]; then the top, if any, is ii's answer
  4. Pop while a[top]>a[i]a[\text{top}] > a[i]; each popped index gets ii as its answer
Show the answer

B. Pop while a[top]>a[i]a[\text{top}] > a[i]; then the top, if any, is ii's answer

Popping every strictly larger value leaves on top the nearest earlier index whose value is at most a[i]a[i]; equal values survive the pop, so they count. Popping is safe for later indices too: a[i]a[i] is closer to them and no larger, so it answers anything the popped indices could have.

Spans, waits, rain water and rectangles

Many classic problems are a nearest greater or smaller element in disguise:

  • Stock span. For each day, how many consecutive days ending today had a price no higher than today's? It is ii minus the index of the previous strictly greater price. For prices [31,27,30,33,29,29,35][31, 27, 30, 33, 29, 29, 35] the spans are 1,1,2,4,1,2,71, 1, 2, 4, 1, 2, 7.
  • Waiting for a warmer day. The distance to the next greater temperature.
  • The largest rectangle in a histogram. A rectangle as tall as bar ii can stretch left to just after the previous smaller bar and right to just before the next smaller one, so the answer is the maximum of h[i]⋅(NS(i)−PS(i)−1)h[i] \cdot (\mathrm{NS}(i) - \mathrm{PS}(i) - 1) over all bars.

Trapping rain water. Bars of heights h[i]h[i] hold water between them. The water above bar ii is the lower of two walls, the highest bar on its left and the highest bar on its right (counting bar ii itself on both sides), minus h[i]h[i]: with LiL_i and RiR_i for those two maxima, it is min⁡(Li,Ri)−h[i]\min(L_i, R_i) - h[i]. A monotonic stack computes the same total layer by layer: when a taller bar arrives, each popped bar is the floor of a pool whose walls are the new top of the stack and the new bar.

python
def trapped_water(h):
    water, stack = 0, []                  # indices; heights never increase upward
    for i, x in enumerate(h):
        while stack and h[stack[-1]] < x:
            bottom = stack.pop()
            if not stack:
                break                     # no wall on the left: the water spills
            left = stack[-1]
            width = i - left - 1
            water += width * (min(h[left], x) - h[bottom])
        stack.append(i)
    return water

O(n)O(n) time and O(n)O(n) space. The two-pointer method needs only O(1)O(1) extra space: move inward from whichever side has the lower wall, since that wall bounds the water there.

Think first How many units of water do bars of heights [3,0,2,0,4,1,2][3, 0, 2, 0, 4, 1, 2] trap?

The water level over each bar is min⁡(left max,right max)\min(\text{left max}, \text{right max}): 3,3,3,3,4,2,23, 3, 3, 3, 4, 2, 2. Subtracting the heights gives 0+3+1+3+0+1+0=80 + 3 + 1 + 3 + 0 + 1 + 0 = 8 units.

Sliding-window maximum: the monotonic deque

Now report the maximum of every window a[i−k+1..i]a[i-k+1..i] of kk consecutive elements (both ends inclusive). Recomputing each window costs O(nk)O(nk); a max-heap that lazily discards expired entries costs O(nlog⁡n)O(n \log n). A monotonic deque costs O(n)O(n).

Keep the indices of the window's candidates in a deque, with values strictly decreasing from front to back. When a[i]a[i] arrives, every candidate at the back with a value ≤a[i]\le a[i] is dominated: it is older and no larger, so it leaves the window first and can never again be the maximum. Pop those from the back and push ii. The front may have slid out of the window: pop it if its index is ≤i−k\le i - k. The front is then the window's maximum.

python
from collections import deque

def window_max(a, k):
    dq, out = deque(), []          # indices; values strictly decrease front to back
    for i, x in enumerate(a):
        while dq and a[dq[-1]] <= x:
            dq.pop()               # dominated: older and not larger
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()           # the front left the window a[i-k+1 .. i]
        if i >= k - 1:
            out.append(a[dq[0]])
    return out

Each index enters the deque once and leaves at most once, from one end or the other, so the total time is O(n)O(n), and the deque never holds more than kk indices. The window advances one position per step, so at most one index expires per step, and a single check of the front suffices.

Check your understanding

Run window_max on [1,3,2,5,4][1, 3, 2, 5, 4] with k=3k = 3. Which values does the deque hold right after the last element is processed?

  1. [5,4][5, 4]
  2. [2,5,4][2, 5, 4]
  3. [4][4]
  4. [3,5,4][3, 5, 4]
Show the answer

A. [5,4][5, 4]

When 5 arrives it dominates 2 and 3, which are popped from the back. Then 4 is pushed behind 5, because it is smaller and may become the maximum once 5 leaves. The front, 5, is the maximum of the last window, [2,5,4][2, 5, 4].

Recognizing it

Signals in a problem statement:

  • "for each element, the nearest, next or previous greater or smaller one", "how far until …", "how many consecutive … before", "who can see whom" along a row of heights;
  • "the maximum or minimum of every window of kk consecutive elements", or a dynamic program whose transition takes a minimum over a sliding range of earlier states;
  • "the sum, over all subarrays, of their minimum or maximum": contribution counting with nearest smaller values;
  • areas bounded by bar heights: rectangles under a histogram, water between walls;
  • nn around 10510^5 to 10610^6, which rules out the obvious O(n2)O(n^2) scan (rule of thumb: about 10810^8 simple operations per second).
Problem (in brief)StructureKey ideaCost
Days until a warmer temperaturemonotonic stacknext greater element, as a distanceO(n)O(n)
Stock spanmonotonic stackprevious strictly greater element, as a distanceO(n)O(n)
Trapped rain watermonotonic stack, or two pointerspop a floor; its walls are the new top and the new barO(n)O(n)
Largest rectangle in a histogrammonotonic stackthe previous and next smaller bars bound each bar's rectangleO(n)O(n)
Maximum of every window of size kkmonotonic dequedrop dominated indices at the back and expired ones at the frontO(n)O(n)
Sum of the minimums of all subarraystwo monotonic stackscontribution a[i](i−L[i])(R[i]−i)a[i](i - L[i])(R[i] - i), strict on one side onlyO(n)O(n)
Look-alikes that do not fit. The median, or the kk-th largest value, of every window is not a single extreme, so domination does not apply: use two heaps or an order-statistics tree, O(nlog⁡k)O(n \log k). Range maxima for arbitrary queries (l,r)(l, r) that do not slide in one direction need a sparse table (O(1)O(1) per query after O(nlog⁡n)O(n \log n) preprocessing) or a segment tree.

Key takeaways

  • A monotonic stack holds the indices still waiting for an answer; each index is pushed once and popped at most once, so every next or previous greater or smaller element takes O(n)O(n) in total.
  • The comparison chooses the question: flip it for greater versus smaller, and use its strictness to decide how repeated values count, remembering that the two directions treat ties oppositely.
  • Spans, waiting times, trapped water, histogram rectangles and sums of subarray minimums are nearest greater or smaller problems in disguise.
  • A monotonic deque drops dominated candidates at the back and expired ones at the front, giving every sliding-window maximum or minimum in O(n)O(n) total time.
  • Medians, kk-th largest values and arbitrary range queries do not fit: no candidate can be discarded, or the range does not slide.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What is the largest possible total number of pops in next_greater on an array of nn elements?

  1. n−1n - 1
  2. n(n−1)/2n(n - 1)/2, since step ii can pop up to ii indices
  3. nlog⁡2nn \log_2 n
  4. 2n2n
Show the answer

A. n−1n - 1

Each index is popped at most once and the last index pushed is never popped, so there are at most n−1n - 1 pops; any increasing array reaches that. A single step can pop many indices, but only indices that earlier steps pushed and nobody popped.

Question 2

You compute the sum of subarray minimums as ∑ia[i] (i−L[i]) (R[i]−i)\sum_i a[i]\,(i - L[i])\,(R[i] - i), but with strictly smaller on both sides. What does that give on [2,2,2][2, 2, 2]?

  1. 6
  2. 12, the true sum
  3. 18
  4. 20
Show the answer

D. 20

With strict comparisons no index has a smaller neighbor, so L[i]=−1L[i] = -1 and R[i]=3R[i] = 3 for all three, and the total is 2⋅(1⋅3+2⋅2+3⋅1)=202 \cdot (1 \cdot 3 + 2 \cdot 2 + 3 \cdot 1) = 20: subarrays with repeated minimums are counted once per copy. A non-strict comparison on one side counts each subarray exactly once and gives 12.

Question 3

Which of these problems is not solved by a single monotonic stack or deque pass?

  1. For each day, the number of days until a warmer one
  2. The maximum of every window of 50 consecutive readings
  3. The median of every window of 50 consecutive readings
  4. The largest rectangle under a histogram
Show the answer

C. The median of every window of 50 consecutive readings

A monotonic structure keeps only the candidates that could still be the extreme value and discards dominated ones. A median depends on every element of the window, so nothing can be discarded; two heaps or an order-statistics tree give O(nlog⁡k)O(n \log k).

Question 4

In window_max, with windows a[i−k+1..i]a[i-k+1..i], when must the front index ff be removed?

  1. When f<i−kf < i - k
  2. When f≤i−kf \le i - k
  3. When f≤i−k+1f \le i - k + 1
  4. When f<if < i
Show the answer

B. When f≤i−kf \le i - k

The window starts at i−k+1i - k + 1, so an index f≤i−kf \le i - k lies outside it. Only index i−ki - k leaves the window at step ii, and if it is still in the deque it is at the front, since every other index in the deque is larger.

Go deeper

Further reading

  • A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 8: nearest smaller elements and the sliding window minimum.
  • CP-Algorithms, "Minimum stack / Minimum queue".
  • O. Berkman, B. Schieber & U. Vishkin, "Optimal doubly logarithmic parallel algorithms based on finding all nearest smaller values," Journal of Algorithms 14(3) (1993), 344–370.