Largest Rectangle in Histogram
Problem
You are given an array heights of non-negative integers describing a histogram: bar i has height heights[i] and width 1, and bars are adjacent. Return the area of the largest axis-aligned rectangle that fits entirely inside the histogram (it may span several consecutive bars, and its height is limited by the shortest bar it covers).
- The histogram has between 1 and 150,000 bars.
- Each height is an integer between 0 and 50,000.
Examples
heights = [3, 1, 4, 4, 6, 2]→12. Height 4 across the three bars at indices 2, 3, 4 (heights 4, 4, 6) gives4 * 3 = 12; the single bar of height 6 gives only 6.heights = [5, 3]→6. Height 3 across both bars beats the lone bar of height 5.heights = [7, 7, 7, 7]→28. One flat rectangle across all four bars.
Hints
- Every maximal rectangle is exactly as tall as some bar
i; it then extends left and right as far as the bars stay at least as tall asheights[i]. - So for each bar you need the nearest shorter bar on the left and on the right. That is a "next smaller element" query.
- A stack of indices with non-decreasing heights answers both boundaries as bars are popped. Append a sentinel
0height to flush the stack at the end.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.