Skip to main content

๐Ÿ“‰ Monotonic Stack

One-line summary: A stack that maintains a strictly increasing or decreasing order โ€” enabling O(n) solutions for "next greater/smaller element" and span problems.


Conceptโ€‹

A monotonic stack is a stack where elements are always in monotonically increasing or decreasing order. When a new element violates the order, pop elements until the invariant is restored โ€” those popped elements have found their answer.

Key insight: each element is pushed and popped at most once โ†’ O(n) total.

  • Decreasing stack โ†’ used for "next greater element"
  • Increasing stack โ†’ used for "next smaller element"

Diagramโ€‹

Monotonic Stack Flow Monotonic Stack Animation


Time & Space Complexityโ€‹

OperationTimeSpace
Build NGE arrayO(n)O(n)
Daily TemperaturesO(n)O(n)
Largest Rectangle in HistogramO(n)O(n)

Common Patternsโ€‹

Pattern 1 โ€” Next Greater Elementโ€‹

function nextGreaterElement(nums) {
const result = new Array(nums.length).fill(-1);
const stack = []; // stores indices
for (let i = 0; i < nums.length; i++) {
while (stack.length && nums[i] > nums[stack[stack.length - 1]]) result[stack.pop()] = nums[i];
stack.push(i);
}
return result;
}

Pattern 2 โ€” Daily Temperaturesโ€‹

function dailyTemperatures(temps) {
const result = new Array(temps.length).fill(0);
const stack = [];
for (let i = 0; i < temps.length; i++) {
while (stack.length && temps[i] > temps[stack[stack.length - 1]]) {
const idx = stack.pop();
result[idx] = i - idx;
}
stack.push(i);
}
return result;
}

When to Useโ€‹

  • Finding next/previous greater or smaller elements
  • Range-based problems with comparisons
  • Span and width problems (largest rectangle, trapping rain)
  • Stock span problems

Pitfallsโ€‹

  • Storing values instead of indices (indices let you compute distances)
  • Forgetting to process remaining elements left in the stack at the end
  • Confusing increasing vs decreasing stack direction

Practice Problemsโ€‹

ProblemDifficultySolution
LC 496 โ€” Next Greater Element IEasyView Solution
LC 739 โ€” Daily TemperaturesMediumView Solution
LC 503 โ€” Next Greater Element IIMedium
LC 901 โ€” Online Stock SpanMedium
LC 84 โ€” Largest Rectangle in HistogramHard
LC 42 โ€” Trapping Rain WaterHard
LC 85 โ€” Maximal RectangleHard
LC 907 โ€” Sum of Subarray MinimumsMedium
LC 456 โ€” 132 PatternMedium
CC โ€” Monotonicity Check (MONOTON)Easy
LC 2104 โ€” Sum of Subarray RangesMedium
LC 316 โ€” Remove Duplicate LettersMedium
LC 402 โ€” Remove K DigitsMedium
LC 581 โ€” Shortest Unsorted Continuous SubarrayMedium
LC 962 โ€” Maximum Width RampMedium
LC 1019 โ€” Next Greater Node in Linked ListMedium
LC 1124 โ€” Longest Well-Performing IntervalMedium
LC 1130 โ€” Minimum Cost Tree From Leaf ValuesMedium
LC 1475 โ€” Final Prices With a Special DiscountEasy
LC 1504 โ€” Count Submatrices With All OnesMedium
LC 1673 โ€” Find the Most Competitive SubsequenceMedium
LC 1793 โ€” Maximum Score of a Good SubarrayHard
LC 2289 โ€” Steps to Make Array Non-decreasingMedium
CC โ€” Stack Operations (STACKOP)Easy
CC โ€” Histogram Area (HISTAREA)Medium

  • Stack โ€” monotonic stack is a specialised stack
  • Sliding Window โ€” sliding window maximum uses monotonic deque

โ† Back to Home ยท ยฉ sparshjaswal