Patterns

MS · Pattern 12

Monotonic Stack

Maintain a stack that is always increasing or decreasing. When you push a new element, pop all elements that violate the order — those are the elements for which the current one is the answer.

Monotonic Stack
Time
O(n)
Space
O(n)

Spot it when

  • Next greater / next smaller element
  • Stock span / daily temperatures
  • Largest rectangle in histogram