Skip to content
DSA Patterns
Menu
Language

Pattern #09

Monotonic Stack

Recommended

Next greater/smaller, histogram rectangles, and temperature waits.

When to use

For each index you need the nearest stricter greater/smaller on the left or right, or a span until a barrier.

Recognition cues

  • Next greater / next smaller element
  • Daily temperatures / online stock span
  • Largest rectangle in histogram

Common pitfalls

  • Strict vs non-strict comparison (affects duplicates)
  • Storing values instead of indices when you need distance
  • Forgetting left and right barriers for histogram

90-second recognition drill

Which pattern fits best?

  • Next greater / next smaller element
  • Daily temperatures / online stock span
  • Largest rectangle in histogram

Interactive

Mental model

A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.

Step 1 of 9
1/9

Next warmer day. Stack keeps decreasing temperatures (by index).

73
0
74
1
75
2
71
3
69
4
72
5
76
6
73
7
stack
∅
Statei=-stack=[]
Key:CurrentActive rangeMatchSettled

How to think about it

Keep a stack of indices whose values are monotone (increasing or decreasing). When a new value breaks the order, pop and resolve those indices: the newcomer is their next greater/smaller. Each index is pushed and popped at most once.

Template shapes

Shape Core move Example
Histogram Increasing stack of indices. A lower bar, or a virtual height 0 at the end, pops. Area is height * (right - left - 1), with right = i and left the new top, or -1 LC 84
Histogram per row A '1' grows the bar and a '0' resets it to 0. Each row then uses the LC 84 stack LC 85
Next greater Decreasing stack. Pop while the current value is greater. The answer is that value, not a distance LC 496
Circular next greater The same decreasing stack over 2n steps, with index k % n. Push only while k < n, so each index is pending once LC 503
Warmer day Decreasing temperatures. When today is warmer than the top, answer[top] = i - top LC 739
Subarray minimums left[i] reaches the previous smaller-or-equal. right[i] reaches the next strictly smaller. Add arr[i] * left[i] * right[i], modulo 10^9+7 LC 907

Complexity baseline

O(n) time (amortized one push/pop per index), O(n) stack space.

From template to problem

  1. Store indices. The answer is a distance, a width, or a value looked up at that index.
  2. Next greater pops a decreasing stack (LC 496, LC 739). Nearest smaller pops an increasing stack (LC 84).
  3. Duplicates care about strictness. LC 907’s left bound is smaller-or-equal and its right bound is strictly smaller.
  4. A circular next-greater walks 2n steps and pushes only while k < n (LC 503). Unresolved indexes stay -1.

Template

Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.

Monotonic Stack · Template
/** Monotonic stack template: next greater element to the right (−1 if none). */
export function nextGreater(nums: number[]): number[] {
  const n = nums.length;
  const ans = new Array<number>(n).fill(-1);
  const stack: number[] = [];
  for (let i = 0; i < n; i++) {
    while (stack.length && nums[stack.at(-1)!]! < nums[i]!) {
      ans[stack.pop()!] = nums[i]!;
    }
    stack.push(i);
  }
  return ans;
}
/** Monotonic stack template: next greater element to the right (−1 if none). */
export function nextGreater(nums: number[]): number[] {
  const n = nums.length;
  const ans = new Array<number>(n).fill(-1);
  const stack: number[] = [];
  for (let i = 0; i < n; i++) {
    while (stack.length && nums[stack.at(-1)!]! < nums[i]!) {
      ans[stack.pop()!] = nums[i]!;
    }
    stack.push(i);
  }
  return ans;
}
#StatusProblemTypeDone
  1. 1#84 Largest Rectangle in HistogramGuide
  2. 2#85 Maximal RectangleGuide
  3. 3#496 Next Greater Element IGuide
  4. 4#503 Next Greater Element IIGuide
  5. 5#739 Daily TemperaturesGuide
  6. 6#907 Sum of Subarray MinimumsGuide