Largest Rectangle in Histogram

hard

Given heights, the heights of adjacent bars each of width 1 in a histogram, return the area of the largest rectangle that fits entirely inside the histogram.

Hints

For each bar, how far can a rectangle of that height extend before a shorter bar stops it?
That range is between the previous smaller and next smaller bars.
An increasing monotonic stack finds both boundaries; measure a bar's rectangle when a shorter bar pops it.

Common doubts

It ensures that when a shorter bar arrives, every taller bar on top has just met its next-smaller boundary, so its rectangle can be finalized right then.
The rectangle spans from just after the new stack top (previous smaller) to just before i (next smaller): width = i - newTop - 1, or i if the stack is empty.
It's shorter than every bar, so it forces the stack to flush and measure all remaining bars at the end.

Interview follow-ups

Build a histogram of consecutive 1s ending at each row of a binary matrix, and run this algorithm on each row's histogram.
Yes — after the loop, keep popping remaining bars using n as the right boundary; the sentinel just folds that into the main loop.

Fun facts

  • This is the canonical monotonic-stack 'rectangle' problem — Maximal Rectangle, Trapping Rain Water (stack variant), and more reduce to it.
  • The previous/next-smaller boundaries here are exactly the spans used in Sum of Subarray Minimums.

Asked at

AmazonGoogleMicrosoftMeta
Frequently Sometimes Occasionally
Example 1
Input: heights = [2,1,5,6,2,3]
Output: 10
The rectangle over the bars of height 5 and 6 has width 2 and area 10.
Example 2
Input: heights = [2,4]
Output: 4
The bar of height 4 alone (area 4) beats both bars at height 2 (area 4 as well).
Constraints

- 1 <= heights.length <= 10^5 - 0 <= heights[i] <= 10^4

Solve this problem →