Largest Rectangle in Histogram

50 min · largestRectangleArea()

A row of bars can hide a much wider rectangle than its tallest bar suggests.

You're given heights, where each number is the height of one bar. Every bar has width 1 and rests on the same baseline. Return the largest area of an axis-aligned rectangle — a rectangle whose sides stay horizontal and vertical — that fits entirely inside the bars.

A few ground rules:

  • A rectangle covers one or more consecutive bars.
  • Its height can't exceed the shortest bar it covers.
  • A height of 0 creates a gap, but it remains part of the input.
  • The answer always fits in a signed 32-bit integer.

Constraints

  • 1 <= heights.length <= 100_000
  • 0 <= heights[i] <= 10_000

Hints

Start with a fixed left edge

Move a right edge across the histogram while tracking the shortest bar in that span. The width and minimum height give you every rectangle for that left edge.

When does a bar learn its full width?

A bar can keep extending right while later bars are at least as tall. The first shorter bar proves that its right boundary has arrived.

Keep unfinished bars in order

Store indices whose heights increase from bottom to top. When a shorter bar arrives, pop every bar it closes. After a pop, the new top marks the first shorter bar on the left, so the closed bar's width is right - left - 1.

Follow-up

Can you explain why each index enters and leaves the stack at most once, even when many bars have the same height?

Visible cases

Examples

Example 1

ready
Input
heights = [
  2,
  1,
  5,
  6,
  2,
  3
]
Expected
10
Why
the two middle bars form a 2 × 5 rectangle

Example 2

ready
Input
heights = [
  2,
  4
]
Expected
4
Why
either both bars at height 2 or the second bar alone gives area 4

Example 3

ready
Input
heights = [
  2,
  1,
  2
]
Expected
3
Why
height 1 stretches across all three bars

Interview signal

Asked at

AmazonGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite