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