Largest Rectangle in Histogram
Picture
Bars [2, 4, 2] contain a height-4 rectangle of width 1, but the better rectangle is height 2 across all 3 bars: area 6. A shorter incoming bar closes rectangles that were waiting to extend.
Predict
If the new shorter bar is at i and the surviving smaller bar is at left, what width belongs to the popped height?
Walk through the small example
i − left − 1. Neither smaller boundary can be included. If there is no smaller bar to the left, use left = −1.
Mental model and complete Python solution
Keep increasing heights by index. Popping a taller bar identifies its right boundary; the new stack top supplies its left boundary. We also pop equal heights: the newer copy inherits the ability to extend left, so a full-width candidate is still considered. A zero sentinel flushes every positive waiting height. Every possible rectangle has a minimum-height bar; at least one such bar gets the full relevant span when popped.
What the function promises: Heights are nonnegative, each bar has width one. Return the maximum area; an empty histogram has area zero. Input is not mutated.
def largest_rectangle(heights):
bars = list(heights) + [0]
stack = []
best = 0
for i, height in enumerate(bars):
while stack and bars[stack[-1]] >= height:
h = bars[stack.pop()]
left = stack[-1] if stack else -1
best = max(best, h * (i - left - 1))
stack.append(i)
return best
assert largest_rectangle([2, 4, 2]) == 6
assert largest_rectangle([2, 2]) == 4
assert largest_rectangle([0, 0]) == 0
assert largest_rectangle([]) == 0
Work and storage: O(n) time and O(n) space: each bar enters and leaves once. The appended sentinel costs O(n) copied storage as well.
When to recognize it: A shorter bar tells taller waiting bars exactly where their rectangle must stop.
Check before applying it: The tallest bar alone may lose to several shorter bars. Equal heights need a consistent boundary rule.
Change one rule
Now find the largest rectangle of 1s in a binary matrix. Can this idea survive?
See what changes
At each row, accumulate consecutive-1 heights for each column, resetting on zero. Run this histogram algorithm for that row. This derives the standard maximal-rectangle method in O(rows × columns), instead of treating it as an unrelated trick.
Connect
Daily Temperatures: Reuse the stack of unresolved candidates.
Burst Balloons: Compare two interval-shaped problems with very different dependencies.
Problem reference: Largest Rectangle in Histogram (Hard). The walkthrough and Python solution above are original course material.