Trapping Rain Water

Hard

Topics
ArrayTwo PointersStack

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1

010210132121
Each bar is one elevation value. The shaded blocks are the water that is trapped, which is what the answer counts — a column holds water up to min(tallest to its left, tallest to its right).
Input:  height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Example 2

420325
Input:  height = [4,2,0,3,2,5]
Output: 9

Constraints

  • 1 <= n <= 2*10^4
  • 0 <= height[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Water sitting above a bar equals min(tallest wall on its left, tallest wall on its right) - the bar’s own height.

With two pointers we always process the side whose max is definitely the limiting one: if the left bar is shorter than the right bar, the left side’s water depends only on leftMax, so we can settle it immediately.

Approach

  1. Pointers l, r plus leftMax, rightMax.
  2. If height[l] < height[r]: update leftMax, add leftMax - height[l], move l right.
  3. Else: update rightMax, add rightMax - height[r], move r left.
  4. Accumulate until the pointers meet.

Walkthrough

height = [4, 2, 0, 3, 2, 5]
right side lower until the 5 at the end;
trapped: above the 2 -> 2, above 0 -> 3, above 3 -> 0, above 2 -> 1... total = 9

Complexity

  • Time — O(n): a single two-pointer pass.
  • Space — O(1): a few scalars (the precompute-arrays version costs O(n)).

Common Pitfalls

  • Update the running max before adding water, or you may subtract more than the wall height.

Full Solution — all languages

class Solution:
    def trap(self, nums):
        if not nums:
            return 0
        lo, hi = 0, len(nums) - 1
        lmax, rmax, res = nums[lo], nums[hi], 0
        while lo < hi:
            if lmax < rmax:
                lo += 1
                lmax = max(lmax, nums[lo])
                res += lmax - nums[lo]
            else:
                hi -= 1
                rmax = max(rmax, nums[hi])
                res += rmax - nums[hi]
        return res
SensAI
Beta
Tap the mic to stop voice mode