Back to Home

Monotonic Stack

A monotonic stack maintains elements in either strictly increasing or decreasing order. It excels at finding the next greater/smaller element, computing spans, and solving problems involving visibility or dominance relationships in sequences.

6
Problems
1
Easy
3
Medium
2
Hard

When to Use

  • -Finding next greater/smaller element
  • -Calculating spans or visibility ranges
  • -Histogram-related problems (largest rectangle)
  • -Trapping water / area calculations

Key Insight

When we encounter an element that breaks the monotonic property, all elements popped from the stack have found their "answer" in the current element.

while stack and nums[stack[-1]] < nums[i]:
  # popped element's NGE is nums[i]

Complexity

Time:O(n)

Each element pushed/popped once

Space:O(n)

Stack can hold all elements in worst case