Largest Rectangle in Histogram

HardMonotonic stackLeetCode 84 ↗World 2-22
0:00 / 0:00

The biggest rectangle under a histogram. Keep a stack of rising bars, and when a shorter bar arrives, pop and measure each taller one.

▼

The problem

LeetCode 84 (Hard). Given the heights of bars that are each one unit wide, return the area of the largest rectangle that fits under the histogram.

Example: [2, 1, 5, 6, 2, 3] → 10 (height 5 across the 5 and the 6, width 2).

def largest_rectangle(heights):
    heights = heights + [0]      # flush the stack
    stack, best = [], 0          # indices, rising
    for i, h in enumerate(heights):
        while stack and heights[stack[-1]] > h:
            top = heights[stack.pop()]
            left = stack[-1] if stack else -1
            best = max(best, top * (i - left - 1))
        stack.append(i)
    return best
TRY IT ON LEETCODE ▶

The solution

def largest_rectangle(heights):
    heights = heights + [0]      # flush the stack
    stack, best = [], 0          # indices, rising
    for i, h in enumerate(heights):
        while stack and heights[stack[-1]] > h:
            top = heights[stack.pop()]
            left = stack[-1] if stack else -1
            best = max(best, top * (i - left - 1))
        stack.append(i)
    return best

Transcript

Largest Rectangle in Histogram. A row of bars stands side by side, each one unit wide. Find the area of the biggest rectangle that fits under them.

Take heights two, one, five, six, two, three. The six alone gives six. The whole row is only one high: six again. The best covers the five and the six: height five, width two, area ten.

The naive way tries every pair of bars. The shortest bar between them sets the height, and the distance sets the width. Six bars make twenty-one pairs, but a hundred thousand bars make five billion. That's n squared: too slow.

Flip it around. The best rectangle is exactly as tall as its shortest bar. So for each bar, stretch a rectangle of its height left and right until it hits a shorter bar. Find those two walls, and you have its area.

A stack finds the walls. It holds indices whose heights rise from bottom to top. When a shorter bar arrives, it's the right wall for every taller bar on top. Pop each one: its left wall is the bar now under it.

In code, add a zero at the end, so every bar gets popped. For each bar, while the top of the stack is taller, pop it. Its width runs between the new bar and the one below it. Keep the best height times width, then push the index.

Let's run it. Push two. One is shorter, so pop two: area two. Push one, five and six. Then two arrives: pop six, area six. Pop five, width two, area ten. Push two and three. The zero flushes the rest: three, then two times four is eight, then one times six is six. The best is ten.

Every bar is pushed once and popped once, so the time is order n. If the heights only rise, the stack holds every bar: order n space.

Keep the heights rising, and pop when they fall. That's Largest Rectangle in Histogram.