LeetCode #84 Hard

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.
Constraints
  • 1 <= heights.length <= 10⁵
  • 0 <= heights[i] <= 10⁴
stackmonotonic-stack
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def largestRectangleArea(self, heights):
▶3 stack, best = [], 0
▶4 for i, h in enumerate(heights + [0]):
▶5 while stack and heights[stack[-1]] > h:
▶6 height = heights[stack.pop()]
▶7 left = stack[-1] if stack else -1
▶8 best = max(best, height * (i - left - 1))
▶9 stack.append(i)
▶10 return best
barsbest area 0215623end 0stack, rising heightsheight × widtheach bar waits on the stack for a shorter bar
heights[2, 1, 5, 6, 2, 3]
best0
The largest rectangle is as tall as the shortest bar it covers. So for every bar, find how far a rectangle of exactly that height can stretch: up to the nearest shorter bar on each side. The stack finds both edges in one pass.
barsbest area 0215623end 0stack, rising heights2topheight × widthpush 2 and let it wait
bar2
stack[2]heights
Nothing on the stack is taller than 2. Push it: its right edge is not known yet.
barsbest area 2215623end 0stack, rising heightsheight × width2×1=2pop 2 → area 2, new best
height2
width1from the start
best2
Bar 1 is shorter, so the bar of height 2 cannot stretch further right. The stack below it is empty, so nothing on its left is shorter: it stretches back to the start. Width 1 gives area 2.
barsbest area 2215623end 0stack, rising heights1topheight × widthpush 1 and let it wait
bar1
stack[1]heights
Nothing on the stack is taller than 1. Push it: its right edge is not known yet.
barsbest area 2215623end 0stack, rising heights15topheight × widthpush 5 and let it wait
bar5
stack[1, 5]heights
5 is at least as tall as the top of the stack, so nothing is settled. Push it; the stack stays in rising order.
barsbest area 2215623end 0stack, rising heights156topheight × widthpush 6 and let it wait
bar6
stack[1, 5, 6]heights
6 is at least as tall as the top of the stack, so nothing is settled. Push it; the stack stays in rising order.
barsbest area 6215623end 0stack, rising heights15topheight × width6×1=6pop 6 → area 6, new best
height6
width1between the shorter bars
best6
Bar 2 is shorter, so the bar of height 6 cannot stretch further right. The bar now on top of the stack, height 5, is the nearest shorter bar on its left. Width 1 gives area 6.
barsbest area 10215623end 0stack, rising heights1topheight × width5×2=10pop 5 → area 10, new best
height5
width2between the shorter bars
best10
Bar 2 is shorter, so the bar of height 5 cannot stretch further right. The bar now on top of the stack, height 1, is the nearest shorter bar on its left. Width 2 gives area 10.
barsbest area 10215623end 0stack, rising heights12topheight × widthpush 2 and let it wait
bar2
stack[1, 2]heights
2 is at least as tall as the top of the stack, so nothing is settled. Push it; the stack stays in rising order.
barsbest area 10215623end 0stack, rising heights123topheight × widthpush 3 and let it wait
bar3
stack[1, 2, 3]heights
3 is at least as tall as the top of the stack, so nothing is settled. Push it; the stack stays in rising order.
barsbest area 10215623end 0stack, rising heights12topheight × width3×1=3pop 3 → area 3, no better
height3
width1between the shorter bars
best10
The input has ended, which acts like a bar of height 0, so the bar of height 3 cannot stretch further right. The bar now on top of the stack, height 2, is the nearest shorter bar on its left. Width 1 gives area 3.
barsbest area 10215623end 0stack, rising heights1topheight × width2×4=8pop 2 → area 8, no better
height2
width4between the shorter bars
best10
The input has ended, which acts like a bar of height 0, so the bar of height 2 cannot stretch further right. The bar now on top of the stack, height 1, is the nearest shorter bar on its left. Width 4 gives area 8.
barsbest area 10215623end 0stack, rising heightsheight × width1×6=6pop 1 → area 6, no better
height1
width6from the start
best10
The input has ended, which acts like a bar of height 0, so the bar of height 1 cannot stretch further right. The stack below it is empty, so nothing on its left is shorter: it stretches back to the start. Width 6 gives area 6.
barsbest area 10215623end 0stack, rising heightsheight × widthanswer: 10
answer10
Every bar has been popped exactly once, and each pop measured the widest rectangle of that bar's height. The largest of those areas, 10, is the answer.
05

Common pitfalls

No flush at the end

✗ Wrong
for i, h in enumerate(heights):
✓ Right
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

✗ Wrong
best = max(best, height * (i - left))
✓ Right
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

✗ Wrong
width = i - popped
✓ Right
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.

06

Edge cases

Falling heights, e.g. [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.

Zero bars, e.g. [0, 0]

A zero bar pops everything before it. The zero bars themselves give area 0, so the answer is 0.

07

Complexity

Time
O(n)
Space
O(n)
Each index is pushed once and popped once, so the inner loop runs at most n times in total across the whole scan. The stack holds up to n indices when heights only rise.
08

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.