Skip to content

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).

15 min read0/5 questions

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 wantStack order (bottom to top)Pop while top isAnswer is read
Next greaterdecreasing< xwhen an index is popped, x is its answer
Next smallerincreasing> xwhen an index is popped
Previous greaterdecreasing<= xafter popping, the top is the answer for x
Previous smallerincreasing>= xafter 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.

Python
def next_greater(nums): """For each i, the index of the first element to the RIGHT that is strictly greater, or -1.""" ans = [-1] * len(nums) stack = [] # indices; values never increase bottom to top for i, x in enumerate(nums): while stack and nums[stack[-1]] < x: ans[stack.pop()] = i # x is the answer for everything it pops stack.append(i) return ans def prev_smaller(nums): """For each i, the index of the nearest element to the LEFT that is strictly smaller, or -1.""" ans = [-1] * len(nums) stack = [] # indices; values strictly increasing for i, x in enumerate(nums): while stack and nums[stack[-1]] >= x: stack.pop() # can never be anyone's previous smaller again ans[i] = stack[-1] if stack else -1 # whatever survives is the answer for i stack.append(i) return ans def next_greater_circular(nums): """Next Greater Element II: values, wrapping around once.""" n = len(nums) ans = [-1] * n stack = [] for i in range(2 * n): # walk the array twice x = nums[i % n] while stack and nums[stack[-1]] < x: ans[stack.pop()] = x if i < n: # only real indices need answers stack.append(i) return ans def brute_next_greater(nums): n = len(nums) return [next((j for j in range(i + 1, n) if nums[j] > nums[i]), -1) for i in range(n)] def brute_prev_smaller(nums): return [next((j for j in range(i - 1, -1, -1) if nums[j] < nums[i]), -1) for i in range(len(nums))] assert next_greater([2, 1, 2, 4, 3]) == [3, 2, 3, -1, -1]assert prev_smaller([3, 1, 4, 1, 5]) == [-1, -1, 1, -1, 3]assert next_greater_circular([1, 2, 1]) == [2, -1, 2]assert next_greater_circular([5, 4, 3, 2, 1]) == [-1, 5, 5, 5, 5] import randomrandom.seed(3)for _ in range(300): a = [random.randint(0, 5) for _ in range(random.randint(0, 10))] assert next_greater(a) == brute_next_greater(a) assert prev_smaller(a) == brute_prev_smaller(a)print(next_greater([2, 1, 2, 4, 3]))print(next_greater_circular([1, 2, 1]))
Output
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 <.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Histogram [2, 1, 5, 6, 2, 3] with a sentinel 0
2
0
1
1
↑i
5
2
6
3
2
4
3
5
0
6
stack = [0]best = 2

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.

1/6
Python
def largest_rectangle(heights): stack = [] # indices, heights increasing best = 0 bars = heights + [0] # sentinel 0 flushes the stack at the end for i, h in enumerate(bars): while stack and bars[stack[-1]] >= h: top = bars[stack.pop()] left = stack[-1] if stack else -1 # previous smaller bar best = max(best, top * (i - left - 1)) # i is the next smaller bar stack.append(i) return best def maximal_rectangle(matrix): if not matrix: return 0 heights = [0] * len(matrix[0]) best = 0 for row in matrix: for c, cell in enumerate(row): heights[c] = heights[c] + 1 if cell == "1" else 0 best = max(best, largest_rectangle(heights)) return best def brute_rect(h): return max((min(h[i:j + 1]) * (j - i + 1) for i in range(len(h)) for j in range(i, len(h))), default=0) assert largest_rectangle([2, 1, 5, 6, 2, 3]) == 10assert largest_rectangle([2, 4]) == 4assert largest_rectangle([3, 3, 3]) == 9assert largest_rectangle([]) == 0import randomrandom.seed(4)for _ in range(300): h = [random.randint(0, 6) for _ in range(random.randint(0, 9))] assert largest_rectangle(h) == brute_rect(h) assert maximal_rectangle([ ["1", "0", "1", "0", "0"], ["1", "0", "1", "1", "1"], ["1", "1", "1", "1", "1"], ["1", "0", "0", "1", "0"],]) == 6print(largest_rectangle([2, 1, 5, 6, 2, 3]))
Output
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.

Python
def trap_stack(height): stack, water = [], 0 # indices, heights decreasing for i, h in enumerate(height): while stack and height[stack[-1]] < h: bottom = height[stack.pop()] if not stack: break # no left wall, water spills out left = stack[-1] width = i - left - 1 depth = min(height[left], h) - bottom water += width * depth # fill one horizontal layer stack.append(i) return water def trap_two_pointers(height): l, r = 0, len(height) - 1 left_max = right_max = water = 0 while l < r: if height[l] < height[r]: # the left side is the limiting wall left_max = max(left_max, height[l]) water += left_max - height[l] l += 1 else: right_max = max(right_max, height[r]) water += right_max - height[r] r -= 1 return water def brute_trap(h): return sum(max(0, min(max(h[:i + 1]), max(h[i:])) - h[i]) for i in range(len(h))) for h in ([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1], [4, 2, 0, 3, 2, 5], [], [5], [3, 0, 3]): assert trap_stack(h) == trap_two_pointers(h) == brute_trap(h)import randomrandom.seed(5)for _ in range(300): h = [random.randint(0, 6) for _ in range(random.randint(0, 12))] assert trap_stack(h) == trap_two_pointers(h) == brute_trap(h)print(trap_stack([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]), trap_two_pointers([4, 2, 0, 3, 2, 5]))
Output
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.

Python
MOD = 10**9 + 7 def sum_subarray_mins(arr): n = len(arr) left = [0] * n # how many start positions make arr[i] the minimum right = [0] * n # how many end positions make arr[i] the minimum stack = [] for i in range(n): # previous STRICTLY smaller while stack and arr[stack[-1]] >= arr[i]: stack.pop() left[i] = i - (stack[-1] if stack else -1) stack.append(i) stack = [] for i in range(n - 1, -1, -1): # next smaller OR EQUAL while stack and arr[stack[-1]] > arr[i]: stack.pop() right[i] = (stack[-1] if stack else n) - i stack.append(i) return sum(arr[i] * left[i] * right[i] for i in range(n)) % MOD def brute(arr): return sum(min(arr[i:j + 1]) for i in range(len(arr)) for j in range(i, len(arr))) % MOD assert sum_subarray_mins([3, 1, 2, 4]) == 17assert sum_subarray_mins([11, 81, 94, 43, 3]) == 444assert sum_subarray_mins([2, 2]) == 6 # [2], [2], [2, 2]: no double countimport randomrandom.seed(6)for _ in range(300): a = [random.randint(1, 4) for _ in range(random.randint(1, 10))] assert sum_subarray_mins(a) == brute(a)print(sum_subarray_mins([3, 1, 2, 4]))
Output
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.

Quick check
In Sum of Subarray Minimums, what happens if you use 'strictly smaller' on both sides?
Need a nudge? A hint rules out a wrong answer.

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:

  1. Drop the front if it has slid out of the window (dq[0] <= i - k).
  2. 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.
  3. Push the new index at the back.
  4. The front is the maximum of the current window.

It is the monotonic stack with one addition: elements also expire from the other end.

Window maximum, k = 3, on [1, 3, -1, -3, 5, 3, 6, 7]
1
0
3
1
↑i
-1
2
-3
3
5
4
3
5
6
6
7
7
deque = [1]out = []

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.

1/6

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, record j - front and pop the front. Any later j would give a longer subarray for that start, so it is finished.
  • Back: while prefix[back] >= prefix[j], pop the back. Index j is a later start with a smaller or equal prefix, so it beats back on both sum and length for every future end.
Python
from collections import deque def max_sliding_window(nums, k): dq = deque() # indices; their values strictly decreasing out = [] for i, x in enumerate(nums): if dq and dq[0] <= i - k: # front index has left the window dq.popleft() while dq and nums[dq[-1]] <= x: dq.pop() # smaller and older: can never be a max again dq.append(i) if i >= k - 1: out.append(nums[dq[0]]) # the front is the max of this window return out def shortest_subarray(nums, k): """Shortest subarray with sum >= k. Negatives allowed. -1 if none.""" prefix = [0] for x in nums: prefix.append(prefix[-1] + x) dq = deque() # indices into prefix; values increasing best = len(nums) + 1 for j, p in enumerate(prefix): while dq and p - prefix[dq[0]] >= k: best = min(best, j - dq.popleft()) # best partner for this start while dq and prefix[dq[-1]] >= p: dq.pop() # later and not larger: a better start dq.append(j) return best if best <= len(nums) else -1 def brute_window(nums, k): return [max(nums[i:i + k]) for i in range(len(nums) - k + 1)] def brute_shortest(nums, k): n = len(nums) lens = [j - i + 1 for i in range(n) for j in range(i, n) if sum(nums[i:j + 1]) >= k] return min(lens, default=-1) assert max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]assert max_sliding_window([4, 4, 4], 2) == [4, 4]assert shortest_subarray([2, -1, 2], 3) == 3assert shortest_subarray([1, 2], 4) == -1assert shortest_subarray([84, -37, 32, 40, 95], 167) == 3import randomrandom.seed(7)for _ in range(300): a = [random.randint(-4, 6) for _ in range(random.randint(1, 10))] k = random.randint(1, len(a)) assert max_sliding_window(a, k) == brute_window(a, k) t = random.randint(1, 12) assert shortest_subarray(a, t) == brute_shortest(a, t)print(max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3))print(shortest_subarray([2, -1, 2], 3))
Output
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.

TypeScript
function maxSlidingWindow(nums: number[], k: number): number[] { const dq: number[] = []; // indices; live part is dq[head..] let head = 0; // popping the front = head++, which is O(1) const out: number[] = []; for (let i = 0; i < nums.length; i++) { if (head < dq.length && dq[head] <= i - k) head++; while (head < dq.length && nums[dq[dq.length - 1]] <= nums[i]) dq.pop(); dq.push(i); if (i >= k - 1) out.push(nums[dq[head]]); } return out;} console.log(maxSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3)); // [3, 3, 5, 5, 6, 7]console.log(maxSlidingWindow([9, 8, 7, 6], 2)); // [9, 8, 7]
Output
Press Run (⌘ Enter) to see what happens.
Quick check
A JavaScript sliding-window-maximum solution uses dq.shift() to drop expired indices. What is the worst-case cost?
Need a nudge? A hint rules out a wrong answer.

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 the pairs0/5 matched

Match each problem to the tool and order.

Choose an item, then its match on the other side.
Put it in order4 steps

Order the steps inside the sliding-window-maximum loop.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Key terms
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.