Python 3D Academyবাংলা

Trapping rain water

🌍 In real life. After a monsoon downpour, look at a row of rooftops of different heights, built wall to wall. Water collects in the dips between taller roofs, and runs off wherever there is no taller roof to hold it. How much water stays?

The heights are a list, each roof one unit wide. This is LeetCode 42, one of the most famous array problems, and two pointers solve it in one pass.

The idea in one sentence: the water above a bar is min(tallest wall to its left, tallest wall to its right) - its height, and two pointers moving in from the ends can settle a bar on the side whose tallest wall so far is lower, because that lower wall is the one that decides.

Its words:

  • left max and right max: the tallest bar seen so far from each end
  • level: how high water can stand over a bar, the lower of the two maxes
  • two pointers: l and r, walking in from the ends (Lesson 36.1)

Step by step, for [3, 0, 2, 0, 4]:

  1. Index 1 (height 0): the tallest to its left is 3, to its right 4. Water stands at 3: 3 units.
  2. Index 2 (height 2): level still 3: 1 unit.
  3. Index 3 (height 0): level 3: 3 units.
  4. The end bars hold nothing. Total: 7.

The plain way works the two maxes out for every bar (O(n²), or O(n) with two extra lists of running maxes). Two pointers need neither list:

Why it is correct. Say h[l] < h[r]. Every bar ever seen on the left is at most left_max, and the bar at r is taller than h[l]. The water over bar l is decided by the lower of its two sides. On the right there is a wall at least h[r] high, and left_max is the tallest on the left, so if left_max is lower than what stands on the right, it is the level; and when h[l] itself is the new left max, the bar holds nothing. Either way left_max - h[l] is exactly right, however the bars between l and r look, so l can move on. The same argument, mirrored, settles r when the right side is lower.

What it costs, by counting. Each step settles one bar and moves one pointer: n − 1 steps, O(n) time, O(1) extra memory. The version with two lists of running maxes is also O(n) time but uses O(n) memory; checking every bar against all the others is O(n²).

def trap(h):
    l, r = 0, len(h) - 1
    left_max = right_max = water = 0
    while l < r:
        if h[l] < h[r]:
            left_max = max(left_max, h[l])
            water += left_max - h[l]
            l += 1
        else:
            right_max = max(right_max, h[r])
            water += right_max - h[r]
            r -= 1
    return water


print(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]))
print(trap([4, 2, 0, 3, 2, 5]))
print(trap([1, 2, 3]), trap([]))

Mistakes and edge cases.

  • Moving the taller side. If the pointer at the taller bar moves, the level on the lower side is still unknown, and the answer comes out too big or too small. Always move the lower side.
  • Using the current bar's neighbours only. The level depends on the tallest wall anywhere to each side, not on the bars next to it: [3, 1, 1, 3] holds 4.
  • Adding before updating the max. water += left_max - h[l] before left_max = max(...) can add a negative amount when h[l] is a new tallest bar.
  • Fewer than 3 bars. Nothing can be held; the loop simply doesn't add anything, and an empty list gives 0 without any special case.

Quiz

  1. What does this print?

    def trap(h):
        l, r = 0, len(h) - 1
        left_max = right_max = water = 0
        while l < r:
            if h[l] < h[r]:
                left_max = max(left_max, h[l])
                water += left_max - h[l]
                l += 1
            else:
                right_max = max(right_max, h[r])
                water += right_max - h[r]
                r -= 1
        return water
    
    
    print(trap([2, 0, 2]), trap([3, 1, 1, 3]))
  2. h[l] = 2 and h[r] = 7. Which pointer moves, and why?

    • l: a wall at least 7 high is on the right, so the left side's max decides bar l
    • r: the taller side always moves
    • Both, to save time
  3. What do the two-pointer solution's time and extra memory come to for n bars?

    • O(n) time, O(1) memory
    • O(n) time, O(n) memory
    • O(n²) time, O(1) memory
  4. trap([3, 0, 2, 0, 4]) should be 7, but this gives 6. Which line is wrong?

    def trap(h):
        l, r = 0, len(h) - 1
        left_max = right_max = water = 0
        while l < r:
            if h[l] > h[r]:
                left_max = max(left_max, h[l])
                water += left_max - h[l]
                l += 1
            else:
                right_max = max(right_max, h[r])
                water += right_max - h[r]
                r -= 1
        return water

Coding tasks

  1. Write trap(heights): how many units of rain water the bars hold, in O(n) time and O(1) extra memory.

  2. Write water_levels(heights): a list with the water above each bar. Build two lists of running maxes, one from the left and one from the right, and use min(left[i], right[i]) - heights[i].