Skip to content
StackDecode
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

  1. Each bar can extend left and right as long as neighbours are at least as tall.
  2. Keep a stack of bar indexes with increasing heights.
  3. 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.
  4. Track the biggest area. A final height-0 bar flushes the stack. O(n).

Watch it run

Loading animation…