Codacoda
Back to Academy

patterns

Monotonic Stack

A monotonic stack maintains elements in either strictly increasing or decreasing order. When a new element violates the monotonic property, elements are popped until the property is restored. This pattern efficiently solves problems that require finding the next greater or smaller element for each position in an array.

Use Cases

  • Finding the next greater element for each position
  • Computing the largest rectangle in a histogram
  • Calculating stock span or daily temperatures

Complexity Analysis

MetricBestAverageWorst
TimeO(n)O(n)O(n)
SpaceO(n)

Visualization

45210801234
Stack:[]
Result:[-, -, -, -, -]
Speed:1x
Array: [4, 5, 2, 10, 8]. Find next greater element for each.Step 1 / 9

Implementation

Output

Click "Run Code" to see output...