The largest rectangle in a histogram
🌍 In real life. A row of shops along a road has fronts of different heights, side by side. A company wants to paint the biggest rectangular advertisement it can across the fronts, without going above any of them. How big can it be?
Each shop is a bar one unit wide. This is LeetCode 84, and a monotonic stack (Lesson 39.3) solves it in one pass.
The idea in one sentence: the best rectangle uses the full height of some bar and stretches left and right until a shorter bar; a stack of indexes with rising heights finds both edges, because when a shorter bar arrives it pops every taller bar, and for a popped bar the shorter bar is its right edge and the bar now below it in the stack is just past its left edge.
Its words:
- histogram: bars side by side, each one unit wide
- monotonic stack: here, indexes whose heights only go up from bottom to top
- edges: the first shorter bar on each side of a bar, which stop its rectangle
Step by step, for [2, 4, 3] (with a 0 added at the end):
- 2 and 4 are pushed: heights rising.
- 3 arrives, shorter than 4: pop 4. Its right edge is 3's index; below it is 2, so 4's rectangle is just itself: 4 × 1 = 4.
- The final 0 pops 3: its left edge is just past 2, its right edge the end: 3 × 2 = 6.
- It pops 2 too: nothing below, so it reaches the start: 2 × 3 = 6. Best: 6.
Why it is correct. Take the best rectangle and its lowest bar b: the rectangle is b's full height, stretched until a shorter bar on each side (or the end). When b is popped, the bar that pops it is the first one to its right that is not taller, and the index below it in the stack is the last one to its left that is shorter, because every bar between them was taller and was popped earlier. So the area worked out at that pop is exactly the rectangle for b, and the maximum over all pops includes the best one. The extra 0 at the end makes sure every bar is popped.
What it costs, by counting. Each index is pushed once and popped once: at most 2n stack steps, O(n) time and O(n) memory for the stack. Trying every pair of edges is O(n²), and every stretch with its minimum is O(n³).
def largest_rectangle(heights):
hs = heights + [0] # a 0 at the end pops everything left
stack, best = [], 0 # stack: indexes, heights rising
for i, h in enumerate(hs):
while stack and hs[stack[-1]] >= h:
top = stack.pop()
left = stack[-1] + 1 if stack else 0
best = max(best, hs[top] * (i - left))
stack.append(i)
return best
print(largest_rectangle([2, 1, 5, 6, 2, 3]))
print(largest_rectangle([2, 4]), largest_rectangle([1, 1]), largest_rectangle([]))Mistakes and edge cases.
- The left edge off by one. The rectangle starts one place after the index below in the stack:
stack[-1] + 1. Without the+ 1it reaches over a shorter bar, and [2, 1, 5, 6, 2, 3] answers 15. - Forgetting the closing 0. Bars still on the stack at the end are never measured: [1, 2, 3] would answer 0. Add a 0, or empty the stack after the loop.
- Storing heights instead of indexes. You need positions to measure widths; heights alone can't say how far a bar reached.
- Changing the caller's list.
heights.append(0)adds a 0 to their list;heights + [0]makes a new one.
Quiz
What does this print?
def largest_rectangle(heights): hs = heights + [0] # a 0 at the end pops everything left stack, best = [], 0 # stack: indexes, heights rising for i, h in enumerate(hs): while stack and hs[stack[-1]] >= h: top = stack.pop() left = stack[-1] + 1 if stack else 0 best = max(best, hs[top] * (i - left)) stack.append(i) return best print(largest_rectangle([3, 1, 3]), largest_rectangle([4, 4, 4]))A bar is popped from the stack. What do the bar that popped it and the index now below it tell you?
- Where its rectangle ends on the right, and that it starts just after the index below
- Its height and its width
- Nothing until the loop ends
Why is the stack method O(n) though it has a while loop inside a for loop?
- Each index is pushed once and popped at most once, so the while loop runs at most n times in total
- The while loop only runs once per bar
- Python's lists are fast
largest_rectangle([2, 1, 5, 6, 2, 3]) should be 10, but this answers 15. Which line is wrong?
def largest_rectangle(heights): hs = heights + [0] stack, best = [], 0 for i, h in enumerate(hs): while stack and hs[stack[-1]] >= h: top = stack.pop() left = stack[-1] if stack else 0 best = max(best, hs[top] * (i - left)) stack.append(i) return best
Coding tasks
Write
largest_rectangle(heights): the area of the largest rectangle that fits under the bars, in O(n).Write
widths(heights): for each bar, how many bars wide its rectangle can be (the stretch around it where no bar is shorter). Equal neighbours extend each other:widths([3, 3])is[2, 2].