CodingNodes / Stack / Largest Rectangle in Histogram System design Space play · ←→ step · R restart

Problem

An array heights describes a bar chart: bar i is one unit wide and heights[i] units tall, and the bars stand side by side with no gaps.

Return the area of the biggest axis-aligned rectangle that fits entirely inside the bars. The rectangle may span several neighbouring bars, but it can be no taller than the shortest bar it covers.

Constraints

  • 1 ≤ heights.length ≤ 10⁵
  • 0 ≤ heights[i] ≤ 10⁴

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each bar is pushed once and popped at most once, and the final sweep touches each leftover entry once.

Space: With rising heights, every bar sits on the stack at the same time.

Scan left to right keeping a stack whose heights rise. When a shorter bar arrives, every taller bar on top has met its right wall: pop it and measure height times distance from its start. The new bar inherits the start of the last bar it popped, because everything in between was at least as tall. Bars left at the end reach all the way to the right edge.