Stacks & queuesAnimated
Largest Rectangle in Histogram
A monotonic stack finds how far each bar can extend.
Time
O(n)
Extra space
O(n)
Use it for
Maximum rectangle area.
How it works
- Each bar can extend left and right as long as neighbours are at least as tall.
- Keep a stack of bar indexes with increasing heights.
- When a shorter bar arrives, pop taller bars: each popped bar’s rectangle is as wide as the gap between the new bar and the bar now on top of the stack.
- Track the biggest area. A final height-0 bar flushes the stack. O(n).
Watch it run
Loading animation…