algorythms
All Patterns
Pattern 12

Monotonic Stack

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.

Time

O(n)

Space

O(n)

Recognize it when

  • Next greater / next smaller element
  • Stock span / daily temperatures
  • Largest rectangle in histogram
Progress0/8
0 solved0 attempted