SDE & MLE Prep

42. Trapping Rain Water

Problem

height is an elevation map of bars, each 1 unit wide. Return how many units of rain water it traps after raining.

Example: [0,1,0,2,1,0,1,3,2,1,2,1] → 6

Constraints: n ≤ 2·10⁴.

Water at i = min(maxLeft, maxRight) - h[i]. With two pointers, the side with the smaller running max is the bottleneck, so its water is already determined: process that side and move inward.

                        █
                █ ~ ~ ~ █ █ ~ █
            █ ~ █ █ ~ █ █ █ █ █ █    (~ = trapped water)
height    0 1 0 2 1 0 1 3 2 1 2 1
water     . . 1 . 1 2 1 . . 1 . .    total = 6

Complexity: O(n) time, O(1) space.

class Solution:
    def trap(self, height: List[int]) -> int:
        l, r = 0, len(height) - 1
        lmax = rmax = water = 0
        while l < r:
            if height[l] < height[r]:
                lmax = max(lmax, height[l])
                water += lmax - height[l]
                l += 1
            else:
                rmax = max(rmax, height[r])
                water += rmax - height[r]
                r -= 1
        return water