Stack Pattern

Monotonic
Stacks

A monotonic stack maintains elements in sorted order by popping any element that violates the invariant before pushing a new one. This O(n) pattern solves next-greater-element, histogram area, and span problems.

What is a monotonic stack?

A monotonic stack keeps its elements in increasing or decreasing order: before pushing, you pop everything that would break the order. It solves "next greater element" and "previous smaller element" problems in O(n) instead of O(n²), because each element is pushed and popped at most once.

function nextGreater(nums) {          // O(n)
  const result = Array(nums.length).fill(-1), stack = [];   // stack of indices
  nums.forEach((n, i) => {
    while (stack.length && nums[stack.at(-1)] < n) result[stack.pop()] = n;
    stack.push(i);
  });
  return result;
}
nextGreater([2, 1, 5, 3]);   // [5, 5, -1, -1]

The key insight

Monotonic Increasing

Bottom to top: smallest → largest. Pop when new element is smaller. Used for: next smaller element, minimum span.

Monotonic Decreasing

Bottom to top: largest → smallest. Pop when new element is larger. Used for: next greater element, maximum span.

Next Greater Element — animated

Input: [2, 5, 4, 10, 8]. For each element, find the first element to its right that is greater.

nextGreater([2,5,4,10,8])step 1/6

// Array state

2
i
5
[1]
4
[2]
10
[3]
8
[4]
→ i=0, val=2. Stack empty, push 0. Stack:[0]→vals[2]

// Pseudocode

1// Next Greater Element — monotonic decreasing stack
2function nextGreater(nums):
3 result = array of -1s
4 stack = [] // indices, vals decrease bottom→top
5 for i from 0 to len(nums) - 1:
6 // pop all elements smaller than nums[i]
7 while stack not empty and nums[stack.top] < nums[i]:
8 idx = stack.pop()
9 result[idx] = nums[i] // nums[i] is NGE for idx
10 stack.push(i)
11 return result // O(n) — each element pushed/popped once

Complexity

Next greater element — each element pushed+popped onceO(n)

Linear time

Largest rectangle in histogramO(n)

Linear time

Daily temperatures / stock spanO(n)

Linear time

Space — stack holds at most n elementsO(n)

Linear time

Largest rectangle in histogram

hist-max-rect.pseudo
1// Largest rectangle in histogram — monotonic stack
2function largestRect(heights):
3 stack = [] // indices, heights increase bottom→top
4 maxArea = 0
5 for i from 0 to len(heights):
6 h = heights[i] if i < len else 0 // sentinel
7 while stack not empty and heights[stack.top] > h:
8 height = heights[stack.pop()]
9 width = i if stack empty else i - stack.top - 1
10 maxArea = max(maxArea, height * width)
11 stack.push(i)
12 return maxArea // O(n)
🔍Why O(n) not O(n²)?
Each element is pushed exactly once and popped at most once. The while loop may run many times in one iteration, but the total number of pop operations across the entire array is bounded by n. This amortised argument makes it O(n) overall.

🎯 Quick Check

What type of monotonic stack would you use for the 'next smaller element' problem?

Monotonic Stacks: summary

Key points

  • Store indices rather than values when you need distances or positions.
  • Decreasing stack → next greater element; increasing stack → next smaller element.
  • Classic problems: daily temperatures, largest rectangle in a histogram, stock span.

Frequently asked questions

›Why is a monotonic stack O(n)?

Each element is pushed once and popped at most once, so the total work over the whole array is linear, even with the inner while loop.