progress

~/problems / Stacks / Monotonic stack

Largest Rectangle in Histogram

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

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.

A histogram of bars 1, 3, 4, 5, 2, 3 with the largest rectangle, 2 high and 5 wide across the last five bars, area 10; the bar of height 2 limits it

More examples: [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.

⭐ Bonus: trying every pair of ends is O(n²) and still passes; a speed test earns a star in 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