Skip to main content

Monotonic Stack

What monotonic stack means, when keeping a stack ordered helps find next greater or smaller values without nested loops.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

A monotonic stack is a stack kept in order.

When a new element breaks that order, you pop until the property is restored.

When to use it

It usually appears when the problem asks for:

  • next greater element
  • next smaller element
  • days until a warmer temperature
  • spans

Common mistake

The classic mistake is treating it like an exotic technique.

In practice, it is just an organized way to say:

“some older elements stopped mattering after this one arrived.”

Better question

Before using it, ask:

  1. does the problem compare each element to future or past neighbors?
  2. is there a group of elements that loses relevance when another appears?
  3. am I repeating too many comparisons in nested loops?

Keep exploring