33/36
Part 8 of 8 · Follow-upsLearn and do

Trapped rain water fills in layers with a decreasing stack

Trapping Rain Water is on the compiled LeetCode lists for OpenAI and Airbnb (2 sources). The lesson on two pointers and the sliding window solves it with a pointer at each end. A decreasing stack of bar indices solves it too.

When a taller bar arrives, pop the bar it beats. That bar is the floor of a pool, the new bar is its right wall, and the bar now on top is its left wall. Fill the pool up to the lower wall:

def trapped(heights):
    water, stack = 0, []
    for i, h in enumerate(heights):
        while stack and heights[stack[-1]] < h:
            floor = heights[stack.pop()]
            if not stack:
                break
            left = stack[-1]
            water += (min(heights[left], h) - floor) * (i - left - 1)
        stack.append(i)
    return water


print(trapped([3, 0, 1, 0, 2, 0, 4]))
Predict

Bars 3, 0, 1, 0, 2, 0, 4. How much water do they hold?

Pick one to see what it prints.
Pick an answer above to see the rest