Three problems about the widest stretch where one bar stays the lowest. The move: find each bar's nearest lower neighbours with one stack pass, then add up what that stretch is worth.
You build tools for an ad platform, a monitoring system and a job scheduler. The three problems on this street look unrelated, but each one hides the same question. For one bar, how far can you reach to the left and to the right before you meet a lower bar?
Inside that stretch the bar is the lowest one. So it decides the height of a banner, the quietest hour of a run, or the height of a free block of machines.
| Problem | The stretch of a bar is | What the stretch is worth |
|---|---|---|
| Sum of the minimum of every run | all runs where the bar is the lowest | height times the starts times the ends |
| Largest banner under a skyline | the widest run where the bar is the lowest | height times width |
| Largest rectangle of ones in a grid | the widest run in one row of heights | height times width, best over the rows |
Here is the second problem on the heights 2, 1, 5, 6, 2, 3. The table lists the nearest lower bar on each side of every bar, and the best banner that has that bar as its lowest.
| Bar | Height | Lower bar on the left | Lower bar on the right | Width | Area |
|---|---|---|---|---|---|
| 0 | 2 | none | 1 | 1 | 2 |
| 1 | 1 | none | none | 6 | 6 |
| 2 | 5 | 1 | 4 | 2 | 10 |
| 3 | 6 | 2 | 4 | 1 | 6 |
| 4 | 2 | 1 | none | 4 | 8 |
| 5 | 3 | 4 | none | 1 | 3 |
The best area is 10. Checking every pair of ends costs about n squared steps, which is 5,000,050,000 for 100,000 bars. The stack pass costs n.
Exercise · Predict the output: The largest area with a closing bar. The stack holds bar positions with rising heights, and a bar of height 0 is added at the end. What does this print?
heights = [2, 4, 2, 5, 3]
stack = []
best = 0
for i, h in enumerate(heights + [0]):
while stack and heights[stack[-1]] >= h:
top = stack.pop()
left = stack[-1] if stack else -1
best = max(best, heights[top] * (i - left - 1))
stack.append(i)
print(best)Keep a stack of bar positions whose heights go up from bottom to top. When the next bar is not higher than the top, the top has met its right edge. That bar is the first one on its right that is not higher. The bar under the top on the stack is its left edge, the nearest lower bar on its left.
Pop the top, measure its stretch from those two edges, and compare the next top. Each bar is pushed once and popped once, so the whole pass costs n steps.
At every step the stack holds the bars that have not met a lower bar yet, with heights that rise. So when a bar is popped, the bar under it is its left edge and the bar that caused the pop is its right edge.
For a rectangle, the stretch is the width between the two edges, i - left - 1, and the area is height times that width. When bars have the same height, the earlier ones pop with a short width. The last of them pops with the full width, so the best area is not lost.
A stack of rising heights gives both edges: the arriving bar pops the top, and the entry below is the left edge.
The stack pass ends with bars still on the stack, the ones that never met a lower bar to their right. Add one bar of height 0 at the end. It is lower than every bar, so it pops them all.
Exercise · Find the bug: The bars that never pop. This finds the largest banner area with the stack pass. It is right for most streets, but it returns 0 for the heights 1, 2, 3. Which line is wrong?
def largest_banner(heights):
stack = []
best = 0
for i, h in enumerate(heights):
while stack and heights[stack[-1]] >= h:
top = stack.pop()
left = stack[-1] if stack else -1
best = max(best, heights[top] * (i - left - 1))
stack.append(i)
return bestThe Academy lesson Monotonic stacks finds the next greater or smaller element in one direction, on top of Stacks. This street does not teach that again. It changes three things.
You use both sides at once. A popped bar gets its right edge from the bar that arrives, and its left edge from the entry below it on the stack. One pass gives both.
You decide the tie rule. For the largest rectangle, ties do not matter, because the last equal bar sees the whole width. For the sum of every run's lowest value, they do. The readings 2, 2, 2 have six runs, and the sum of their lowest values is 12.
If both sides stop at a strictly lower bar, every run is counted for each of its equal bars, and the code returns 20. If both sides stop at an equal or lower bar, the code returns 6. Let the left side stop at a strictly lower bar and the right side at an equal or lower bar, and each run is counted once: 12.
A grid becomes a row of bars. In row r, the height of a column is the number of unbroken free cells that end at row r. A taken cell resets the height to 0. The largest free block ends on some row, so the best bar chart area over all rows is the answer.
The reset is where the grid goes wrong. Take one column whose cells are 1, 0, 1 from top to bottom. Without the reset the heights are 1, 1, 2, and the code reports a block of 2 cells. The right heights are 1, 0, 1, and the largest block has 1 cell.
Exercise · Break it: Heights that never reset. This builds the heights of one row from the heights above it. It adds 1 for a free cell and keeps the old height for a taken cell. Find a row where its heights are wrong.
def next_heights(previous, row):
heights = []
for i in range(len(row)):
heights.append(previous[i] + row[i])
return heightsA taken cell must reset a height to 0. Keeping the old height describes a block with a gap.
Solve them in this order. The first one needs the tie rule, the second is the plain pass, and the third builds a bar chart for each row.
Before you code each problem, write three lines. What is a bar here, what are its two edges, and what is the stretch worth? If the edges are the nearest lower bars, one stack pass answers it.
Give each problem about 25 minutes. Draw the bars for the heights 2, 1, 5, 6, 2, 3 and mark the edges of each bar before you write code.
Then test three inputs on every rung. A list with one bar, a list that only rises, and a list of equal bars. They catch the missing closing bar and a wrong tie rule.
When an answer is wrong, print the left and right edge of every bar. Most errors on this street are one edge off by one, or a tie that counts twice.
Checkpoint · Histograms and rectangles
Q1/5 A bar is popped from the stack of rising heights. Where is its left edge, the nearest lower bar on its left?
Answer: B
The stack keeps the bars that have not met a lower bar. After the pop, the entry on top is the nearest lower bar on the left. The bar that arrives is the right edge.
Q2/5 What is the stretch of a popped bar, written with the position i of the bar that caused the pop and the left edge left?
Answer: B
The edges are not part of the stretch. The bars strictly between them count, which is i - left - 1.
Q3/5 The heights are 1, 2, 3. Why must you add a closing bar of height 0 to the stack pass?
Answer: B
A bar of height 0 is lower than every bar, so it pops all that remain. Without it the pass returns 0 for the heights 1, 2, 3, and the answer is 4.
Q4/5 You add up the lowest value of every run of the readings 2, 2, 2, and both sides stop at a strictly lower bar. What goes wrong?
Answer: B
Run the three bars: each of the six runs has several lowest bars, and each of them counts the run. Let one side stop at an equal bar, and each run is counted once.
Q5/5 In a grid of 0 and 1, you build heights row by row. What happens to a height when the cell is 0?
Answer: C
A taken cell breaks every block that passes through it. A height that kept its old value would describe a block with a gap in it.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.