Python coding

Rain trapped between bars

heights[i] is the height of a bar of width 1, and the bars stand side by side with no gaps. Rain fills every dip between them up to where it would spill over, and water above either end runs off. Return how many units of water stay trapped. Heights are non-negative integers.

Aim for O(n) time and O(1) extra space.

Besides the tests, one large input (8,000 bars) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • trapped_rain([3,0,2,0,4]) → 7
  • trapped_rain([0,2,0,3,1,0,1,3,2,1,2,1]) → 10
  • trapped_rain([4,1,2,5,0,3]) → 8
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Above bar i, water rises to the lower of the tallest bar on its left and the tallest on its right, counting bar i itself. Two pointers from the ends can track both.

Hint 2

Keep left_max and right_max from the two ends. Settle the next bar on the side whose maximum is lower: the other side is already at least that tall.

Solution and why it works
pythonO(n) · O(1)
def trapped_rain(heights: list[int]) -> int:
    lo, hi = 0, len(heights) - 1
    left_max = right_max = water = 0
    while lo <= hi:
        if left_max <= right_max:            # the left side is the binding limit
            left_max = max(left_max, heights[lo])
            water += left_max - heights[lo]
            lo += 1
        else:                                # the right side is the binding limit
            right_max = max(right_max, heights[hi])
            water += right_max - heights[hi]
            hi -= 1
    return water

Water above a bar rises to the lower of the tallest bar on its left and on its right. Track the tallest bar seen from each end and settle the next bar on the side whose maximum is lower: that maximum is the binding limit, because the other side already has a bar at least as tall. Each step settles one bar for good: O(n) time, O(1) space. Rescanning both sides for every bar is the O(n²) trap.

Related lab: Loops in motion