Largest Rectangle in Histogram
Largest Rectangle in Histogram is LeetCode 84 (Hard). You get an array heights. Each value is the height of a bar of width 1, and the bars stand side by side. Return the area of the largest rectangle that fits inside the histogram.
- There can be up to 10⁵ bars, so trying every pair of left and right edges (about 5·10⁹ pairs) is too slow. The target is a single pass.
- Heights can be 0, and a zero bar splits the histogram.
- 1 <= heights.length <= 10⁵
- 0 <= heights[i] <= 10⁴
Intuition
A rectangle inside the histogram is only as tall as the shortest bar it covers. So the best rectangle has the height of some bar, and stretches left and right until it meets a shorter bar.
That means each bar needs its nearest shorter bar on both sides. Keep a stack of bars with rising heights. When a shorter bar arrives, the bar on top can stretch no further right, so it is settled right then:
- Right edge: the bar that just arrived.
- Left edge: the bar now under it on the stack, since everything between them was taller and already popped.
One push and one pop per bar gives every candidate rectangle.
"For every element, find the nearest smaller (or larger) element on each side" is the job of a monotonic stack. Here the area for each bar depends on exactly those two neighbours.
Approach
Before reading on, take [2, 1, 5, 6, 2, 3] and, for the bar of height 5, point to the nearest shorter bar on each side. What width does that give? Now ask which bar tells you the right edge, and when you first see it.
Keep a stack of rising bars
Scan the bars left to right and push each index onto a stack. Keep the heights on the stack in rising order. A bar on the stack is one whose right edge has not been found yet.
Pop when a shorter bar arrives
While the current bar is shorter than the bar on top, pop the top. The current index i is the first shorter bar on its right. The new top left is the nearest shorter bar on its left, or -1 if the stack is empty.
Measure the popped bar
The rectangle covers the bars strictly between left and i, so its width is i - left - 1 and its area is the popped height times that width. Keep the largest area seen.
Flush with a bar of height 0
Run the loop one step past the end with height 0. It is shorter than every real bar, so every bar still waiting gets popped and measured by the same code, with no second loop after the scan.
Why equal heights are safe
With a strict > test, equal bars both stay on the stack. The later one is measured too narrow, but the earlier one pops after it and spans the whole run, so the best area is still found.
Code in Python, C++ and Java
Common pitfalls
No flush at the end
for i, h in enumerate(heights):
for i, h in enumerate(heights + [0]):
Bars that never meet a shorter bar stay on the stack and are never measured. On [1, 2, 3] nothing pops, so the function returns 0 instead of 4.
Width one bar too wide
best = max(best, height * (i - left))
best = max(best, height * (i - left - 1))
Both left and i are shorter bars, so neither belongs to the rectangle. On [2, 4] the bar of height 4 sits between left = 0 and i = 2; the wrong width is 2, giving 8 instead of 4.
Using the popped index as the left edge
width = i - popped
left = stack[-1] if stack else -1 width = i - left - 1
Taller bars to the left of the popped bar were popped earlier, but the rectangle still covers them. On [2, 1, 2] the bar of height 1 gets width 2 instead of 3, so the answer is 2 instead of 3.
Edge cases
[5, 4, 3, 2, 1]Every new bar pops the one before it at once. The stack is always empty below the popped bar, so each width reaches back to the start, and the best is 3 × 3 = 9.
[0, 0]A zero bar pops everything before it. The zero bars themselves give area 0, so the answer is 0.
Complexity
Largest Rectangle in Histogram FAQ
How does this solve Maximal Rectangle?
In a grid of 0s and 1s, treat each row as the floor of a histogram whose bar heights count the 1s stacked above each cell. Run this stack pass on every row and keep the best area, for O(rows × cols) in total. See Maximal Rectangle.
Can it be done with two arrays instead of one stack pass?
Yes. One pass from the left records each bar’s nearest shorter bar on the left, a second pass from the right records the nearest shorter bar on the right, and a third pass multiplies. It is still O(n) and easier to check by hand, but it uses two extra arrays and three passes.