Monotonic Stack and Deque

Keep a stack or deque in sorted order to find next greater elements, largest rectangles and sliding window maximums in linear time.

Intermediate · about 6 hours · difficulty 4/5

Learn first: Queues and Deques, Sliding Window

A monotonic stack keeps its elements in increasing or decreasing order by popping anything that would break the order before pushing. Each element is pushed and popped at most once, so the whole scan is O(n).

Next greater element

Scan left to right with a stack of indices whose next greater element is not yet known, kept in decreasing order of value. When a new value is larger than the top, the top has found its answer: pop it and record. This single idea solves:

  • Next Greater Element, Daily Temperatures.
  • Previous smaller / next smaller element (flip the comparison or the scan direction).
  • Largest Rectangle in Histogram: for each bar, the nearest smaller bars on the left and right bound its widest rectangle.
  • Sum of Subarray Minimums: count how many subarrays each element is the minimum of.
  • Stock Span, Remove K Digits, and Trapping Rain Water (stack version).

Monotonic deque

For sliding window maximum, keep a deque of indices with decreasing values. Pop from the back while the new value is larger (those can never be the maximum again), and pop from the front when the index leaves the window. The front is always the window maximum. It also speeds up some DP transitions (for example "jump game with window").

Tips

Store indices, not values, so you can compute distances and check window bounds. Decide carefully between strict and non-strict comparisons when duplicates exist, or you will double-count.

Key concepts

  • Next greater / smaller element
  • Previous greater / smaller element
  • Largest rectangle in histogram
  • Contribution counting with stacks: Sum of subarray minimums
  • Sliding window maximum deque
  • Handling duplicates strictly
  • Deque-optimised DP

Mini project

Solve 8 problems: Next Greater Element I, Daily Temperatures, Online Stock Span, Largest Rectangle in Histogram, Maximal Rectangle, Sum of Subarray Minimums, Remove K Digits, and Sliding Window Maximum.

Check yourself

Why is the monotonic stack solution O(n) even though there is a while loop inside the for loop?

Free resources