Monotonic Stack & Queue Patterns

Unresolved next-greater questions

Indices increase, values are nonincreasing. Pop while old < new, not on equality. [3,3,1,4,2] → [4,4,4,-1,-1]. An index was not resolved earlier, so its pop identifies the first greater value.

1 / 5

Histogram pops finalize boundaries

Stack heights are nondecreasing. At right boundary i, pop h; new top j or -1. Candidate width is i-j-1. The current smaller bar is excluded.

2 / 5

Equal heights need consistent ownership

[2,4,4,1] at i=3: pop areas 4,8,6; final flush gives 4. Maximum 8. The first popped 4 has an equal-height left boundary. The earlier 4 later owns width 2.

3 / 5

Account for unfinished bars and total work

Virtual end height 0 flushes positive bars without reading heights[n]. Each index is pushed once and popped at most once: O(n) total work. Deque transfer: expiration at the front is separate from dominance at the back.

4 / 5

Reconstruct independently

Next-greater [2,2,3,1] → [3,3,-1,-1]. Histogram [3,3,2] → area 6. Explain equal-height ownership. Verify by enumerating all small histogram ranges, not by copying the same stack algorithm.

5 / 5
←/→ or click edges to navigate · ? help · N notes · F fullscreen