Lesson 13 of 40More array patterns
Monotonic Stacks and Queues
Keep a stack or deque in sorted order to find next greater and smaller elements, histogram areas and sliding window maximums in O(n).
A trading screen shows, for every tick, how long until the price beats it. A metrics service shows the peak latency over the last five minutes, updated every second. A layout engine asks, for each bar in a chart, how far it can stretch before something shorter blocks it. Each of these looks like a nested loop: for every element, scan until something happens. A monotonic stack or deque answers all of them in one pass. You saw the basic version in Stack with Daily Temperatures. This lesson picks up from there with the four flavours, the duplicate trap, histograms, contribution counting and the monotonic deque.
The invariant, and why it is O(n)
A monotonic stack holds indices whose values are in sorted order from bottom to top. Before you push index i, you pop every index whose value would break the order. The pop is not lost work: the element that causes a pop is the answer for the element being popped. In "next greater", a popped index has just met the first larger value to its right.
The cost argument is short and worth saying out loud in an interview. Each index is pushed exactly once. Each index is popped at most once, because once it leaves it never comes back. So across the whole run there are at most n pushes and n pops, which is O(n) total, even though there is a while inside the for. That is an amortised bound: one iteration can pop many items, but the total is capped.
Space is O(n) in the worst case. A strictly decreasing input for "next greater" never pops, so every index waits on the stack until the end.
Four flavours, one template
Every "nearest element with a property" question is one of four. Two choices pick the flavour: which direction you look (next means to the right, previous means to the left), and which comparison you want (greater or smaller).
| You want | Stack order (bottom to top) | Pop while top is | Answer is read |
|---|---|---|---|
| Next greater | decreasing | < x | when an index is popped, x is its answer |
| Next smaller | increasing | > x | when an index is popped |
| Previous greater | decreasing | <= x | after popping, the top is the answer for x |
| Previous smaller | increasing | >= x | after popping, the top is the answer for x |
The "next" flavours answer the popped element. The "previous" flavours answer the current element, using whatever survived the pops. You can also get "next" by scanning right to left and reading the survivor, which some people find easier to remember. Pick one style and practice it until it is automatic.
Press Run (⌘ Enter) to see what happens.Circular arrays. In Next Greater Element II the array wraps, so the next greater element for the last item might be at the start. Walk indices 0 to 2n - 1 and read nums[i % n]. The second lap only answers indices still waiting; it does not push new ones. That is still O(n), with at most 2n iterations and n pushes.
Strict or not: duplicates decide the answer
< versus <= in the pop condition is the most common bug in this pattern. With <, equal values stay on the stack, so an element's "next greater" is strictly greater. With <=, an equal value pops the earlier one, which turns the question into "next greater or equal". Read the problem, then choose. For "how many days until a warmer day", a day of the same temperature is not warmer, so you need <.
What does this print?
nums = [2, 2, 1]
stack, ans = [], [-1, -1, -1]
for i, x in enumerate(nums):
while stack and nums[stack[-1]] <= x:
ans[stack.pop()] = i
stack.append(i)
print(ans)For counting problems, which you will meet below, the choice is not about the problem statement. It is about not counting the same subarray twice.
Largest Rectangle in Histogram
Given bar heights, find the largest rectangle that fits under them. For each bar, the widest rectangle of exactly that height stretches left until the previous smaller bar and right until the next smaller bar. So the answer for bar j is height[j] * (next_smaller - prev_smaller - 1).
One increasing stack gives you both boundaries at once. When bar i pops bar j, then i is j's next smaller bar, and the index now on top of the stack (after the pop) is j's previous smaller bar. A sentinel height of 0 appended at the end is smaller than everything, so it pops whatever is left and you do not need a second cleanup loop.
Bar 1 (height 1) is lower than bar 0, so pop 0. Nothing is left below it, so it stretches from −1 to 1: width 1 − (−1) − 1 = 1, area 2.
Press Run (⌘ Enter) to see what happens.This code pops on >=, so for a run of equal bars the earlier ones compute a width that is too short. That is fine: the last bar in the run computes the full width, and you only need the maximum. In a counting problem, the same shortcut would be a bug.
Maximal Rectangle (largest rectangle of 1s in a binary matrix) reduces to this. Process the matrix row by row, and keep heights[c] as the number of consecutive 1s ending at the current row in column c. Each row is a histogram. Run the histogram solver on each one: O(rows × cols) total. Turning a 2D problem into a series of 1D problems is a move senior engineers reach for often.
Trapping Rain Water: stack or two pointers
Water above bar i is min(max to the left, max to the right) - height[i]. You can solve it three ways in O(n): precomputed left-max and right-max arrays (the left pass and right pass from Prefix Sums and Difference Arrays), two pointers, or a decreasing stack.
The stack version fills water in horizontal layers. When a taller bar arrives and pops a lower "bottom", the new top of the stack is the left wall and the current bar is the right wall. The layer between them has depth min(left wall, right wall) - bottom and width i - left - 1.
The two-pointer version fills water column by column. Move inward from whichever side has the lower wall, because that side's water level is already decided by its own running maximum.
Press Run (⌘ Enter) to see what happens.Which to pick? Two pointers uses O(1) extra space and is the usual expected answer. The stack version works in a single left-to-right pass without knowing the right end, so it fits streaming input, and its layer-by-layer idea generalises to related problems. Mention both, write the one you can get right first time.
Sum of Subarray Minimums: the contribution technique
"Sum the minimum of every subarray, modulo 10^9 + 7." There are about n²/2 subarrays, so listing them is too slow for n = 30,000. Flip the question: for each element, in how many subarrays is it the minimum? If arr[i] is the minimum of a subarray, that subarray can start anywhere after the previous smaller element and end anywhere before the next smaller element. If there are left[i] choices of start and right[i] choices of end, then arr[i] contributes arr[i] * left[i] * right[i].
The trap is ties. In [2, 2] the subarray [2, 2] has two elements that are both "the minimum". If both claim it, you count it twice. Fix it by breaking ties on one side only: look left for a strictly smaller element and right for a smaller or equal one. Then each subarray's minimum is assigned to exactly one index (the leftmost of the tied minimums). This asymmetric rule appears in every contribution problem: Sum of Subarray Ranges, count of subarrays where an element is the maximum, and so on.
Press Run (⌘ Enter) to see what happens.In Python the total never overflows, so taking the modulo once at the end is fine. In Java or C++, arr[i] * left[i] * right[i] can exceed 64 bits only in extreme cases, but the running sum can exceed 32 bits easily. Use 64-bit integers and apply the modulo inside the loop.
The monotonic deque: Sliding Window Maximum
"Return the maximum of every window of size k." A heap works in O(n log k) with lazy deletion. A monotonic deque does it in O(n). Keep indices in a deque whose values are decreasing from front to back. For each new index:
- Drop the front if it has slid out of the window (
dq[0] <= i - k). - Pop from the back every index whose value is
<=the new value. Those elements are older and not larger, so they can never be the maximum of any future window. - Push the new index at the back.
- The front is the maximum of the current window.
It is the monotonic stack with one addition: elements also expire from the other end.
Push 0. Then 3 arrives and pops 1 from the back: an older, smaller value can never be a window max while 3 is around.
Shortest Subarray with Sum at Least K
This is the hard one, and it is the problem Sliding Window warned about: shortest subarray with sum at least k when negatives are allowed. Work on prefix sums. A subarray i..j-1 qualifies when prefix[j] - prefix[i] >= k, and you want the smallest j - i. Keep a deque of candidate start indices with increasing prefix values.
- Front: while
prefix[j] - prefix[front] >= k, recordj - frontand pop the front. Any laterjwould give a longer subarray for that start, so it is finished. - Back: while
prefix[back] >= prefix[j], pop the back. Indexjis a later start with a smaller or equal prefix, so it beatsbackon both sum and length for every future end.
Press Run (⌘ Enter) to see what happens.Deques in Python and TypeScript
In Python, collections.deque gives O(1) append, pop, appendleft and popleft. Do not use a list with pop(0), which shifts every element and is O(n).
JavaScript has no built-in deque, and Array.prototype.shift is O(n) because it reindexes the array. Engines sometimes optimise small arrays, but you cannot rely on that, and on a 10^5 element input an O(n) shift inside a loop is the difference between passing and timing out. Keep a head index instead and treat dq[head..] as the live part. Memory only grows to n, which is fine for a single pass. For long-running queues, use a ring buffer.
Press Run (⌘ Enter) to see what happens.dq.shift() to drop expired indices. What is the worst-case cost?Recognising the pattern
The signal words are next, previous, nearest, until, span, how far can it extend and max or min of every window. If the brute force is "for each element, scan outward until a bigger or smaller one", you want a monotonic stack. If it is "max or min over a moving window", you want a monotonic deque. If it is "sum over all subarrays of their min or max", you want contribution counting with previous and next smaller (or greater).
Match each problem to the tool and order.
Order the steps inside the sliding-window-maximum loop.
- Tap the steps below in the right order.
Practice
All of these are in Practice: Daily Temperatures, Next Greater Element I and II, Largest Rectangle in Histogram, Maximal Rectangle, Trapping Rain Water, Sum of Subarray Minimums and Sliding Window Maximum. For each, decide the direction, the order and the strictness before you write the loop, and test with a run of equal values.
- monotonic stack
- A stack of indices kept in increasing or decreasing value order, popping whatever breaks the order.
- monotonic deque
- A double-ended queue kept in sorted order that also drops expired elements from the front, used for window max and min.
- amortised O(n)
- Each index is pushed once and popped at most once, so the total work is linear even with a while loop inside a for loop.
- sentinel
- An extra value, such as a height of 0 at the end, that forces the loop to finish leftover work without special cases.
- contribution technique
- Sum an answer over all subarrays by counting, for each element, how many subarrays it is the min or max of.
- strict vs non-strict
- Whether the pop condition uses
<or<=. It decides how ties are handled and prevents double counting.