Skip to main content

Monotonic Stack & Queue

Specialized data structures that maintain elements in a sorted (monotonic) order, enabling efficient solutions for “next greater/smaller” problems.

Monotonic Stack

A stack where elements are kept in strictly increasing or decreasing order.

How It Works

  • When pushing a new element, pop all elements that violate the monotonic property
  • The popped elements have “found” their answer (the current element)

Types

  • Monotonically Increasing — finds next smaller element
  • Monotonically Decreasing — finds next greater element

Template (Next Greater Element)

Time & Space: O(n) each

Monotonic Deque (Queue)

A double-ended queue maintaining monotonic order — used for sliding window min/max problems.

Template (Sliding Window Maximum)

Classic Problems

  • Next Greater Element I, II
  • Daily Temperatures
  • Largest Rectangle in Histogram
  • Trapping Rain Water
  • Sliding Window Maximum
  • Shortest Subarray with Sum at Least K
  • Stock Span Problem
  • Remove K Digits

When to Use

  • “Next greater/smaller element” patterns
  • Sliding window min/max queries
  • Histogram-based area problems
  • Problems requiring efficient range extrema