~/problems / Stacks / Monotonic stack

Largest Rectangle in Histogram

hard ~40 min

Write largest_rectangle_area(heights: list[int]) -> int.

heights describes a histogram of adjacent bars, each 1 unit wide. Return the area of the largest axis-aligned rectangle that fits entirely inside the bars.

Example: [1, 3, 4, 5, 2, 3] gives 10: height 2 across the last five bars. [4, 4, 2] gives 8, and [6] gives 6.

Constraints: 1 <= len(heights) <= 2 * 10^5, 0 <= heights[i] <= 10^9. The area can exceed 32 bits.

Trying every pair of ends is O(n²) and fails the large test. Aim for O(n).

Show hint

the best rectangle is as tall as some bar, and then it stretches until the nearest shorter bar on each side. How can you find those limits for every bar in one or two passes?

Topic: Monotonic stack. Next greater/smaller element in O(n); histogram rectangles; trapping water.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc