roadmap/two-pointers/Trapping Rain Water

Trapping Rain Water

HardAmazonGoogleMetaAppleBloomberg
Solve on LeetCode ↗

Given n non-negative integers representing an elevation map, compute how much water it can trap after raining.

Water above position i = min(maxLeft[i], maxRight[i]) - height[i]. With two pointers: if maxLeft < maxRight, the water at left pointer is determined by maxLeft alone — process it and move left inward. Otherwise process right.

Two pointer O(1) space

lo=0, hi=n-1, maxL=0, maxR=0. While lo<hi: if maxL<=maxR, water[lo]=maxL-height[lo], update maxL, lo++. Else water[hi]=maxR-height[hi], update maxR, hi--.

Time
O(n)
Space
O(1)

Single pass, two pointers, constant extra space.

Python
def trap(self, height: List[int]) -> int:
    lo, hi = 0, len(height) - 1
    maxL = maxR = water = 0
    
    while lo < hi:
        if maxL <= maxR:
            maxL = max(maxL, height[lo])
            water += maxL - height[lo]
            lo += 1
        else:
            maxR = max(maxR, height[hi])
            water += maxR - height[hi]
            hi -= 1
    
    return water
Empty or single element: return 0
Monotonically increasing/decreasing: no water trapped

What pattern do you think this problem uses?

Progress is saved on this device