Skip to content
StackDecode
Stacks & queuesAnimated

Monotonic Stack

A stack kept in sorted order by popping items that break the order.

Time

O(n)

Extra space

O(n)

Use it for

Nearest greater/smaller and histogram problems.

How it works

  1. A monotonic stack is kept in strictly decreasing order from bottom to top.
  2. Before pushing a new item, pop every item on top that is smaller or equal (they can never be the "next greater" for anything again).
  3. Then push the new item.
  4. Each item is pushed and popped at most once, so the whole thing is O(n).

Watch it run

Loading animation…