Practice Discrete Math

Algorithms / Monotonic Stack Next Greater

Least You Need to Know: Monotonic Stacks and Next-Greater Patterns

A monotonic stack keeps elements in sorted stack order so that a new value can resolve many waiting positions at once. This turns repeated scanning into a single left-to-right pass for next-greater and waiting-time style problems.

The least you need to know

Key notation

stack LIFO structure holding unresolved candidates
monotone decreasing stored values decrease from bottom to top
next greater first later value strictly larger than the current one

Tiny worked example

  • Scan array values from left to right.
  • Keep a decreasing stack of indices whose next greater value has not appeared yet.
  • When a larger value arrives, pop all smaller indices and record the new value or new index as their answer.
  • Then push the current index.

Common mistakes

How to recognize this kind of problem

Start practice