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
- A monotonic stack is kept in strictly decreasing order from bottom to top.
- 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).
- Then push the new item.
- Each item is pushed and popped at most once, so the whole thing is O(n).
Watch it run
Loading animation…