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.
// Array state
// Pseudocode
Complexity
Linear time
Linear time
Linear time
Linear time
Largest rectangle in histogram
1// Largest rectangle in histogram — monotonic stack2function largestRect(heights):3 stack = [] // indices, heights increase bottom→top4 maxArea = 05 for i from 0 to len(heights):6 h = heights[i] if i < len else 0 // sentinel7 while stack not empty and heights[stack.top] > h:8 height = heights[stack.pop()]9 width = i if stack empty else i - stack.top - 110 maxArea = max(maxArea, height * width)11 stack.push(i)12 return maxArea // O(n)
🎯 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.