← DSA
HARD

Trapping Rain Water

PracticeNeetCode ↗LeetCode ↗

Given n non-negative integers height representing an elevation map where each bar has width 1, compute how much water it can trap after it rains.

Example

Input height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output 6

Key Pointers

Step-by-Step Analysis

  1. Set left = 0, right = len(height) - 1, left_max = 0, right_max = 0, water = 0.
  2. While left < right: if height[left] < height[right], update left_max = max(left_max, height[left]), add left_max - height[left] to water, then advance left.
  3. Otherwise, update right_max = max(right_max, height[right]), add right_max - height[right] to water, then pull right back.
  4. Repeat until the pointers meet; return water.

Complexity

Time: O(n) — Space: O(1)

Code

def trap(height: list[int]) -> int:
    left, right = 0, len(height) - 1
    left_max, right_max = 0, 0
    water = 0

    while left < right:
        if height[left] < height[right]:
            left_max = max(left_max, height[left])
            water += left_max - height[left]
            left += 1
        else:
            right_max = max(right_max, height[right])
            water += right_max - height[right]
            right -= 1

    return water

Code Explanation

How the solution above works, piece by piece.

  1. Pointers at both ends, plus left_max and right_max: the tallest wall seen so far from each side.
  2. if height[left] < height[right]: the left side is lower, so the water over left depends only on left_max. A wall at least as tall as height[right] is guaranteed on the right.
  3. Update left_max, add left_max - height[left] (0 if this bar is the new max) and move left right.
  4. Otherwise do the mirror image on the right side.
  5. Every bar is processed once: O(n) time and O(1) space, versus O(n) space for precomputed left-max/right-max arrays.

Visual Walkthrough

Running it on height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]:

Elevation map with 6 units of trapped water010210132121+1+1+2+1+1water at i = min(max left, max right) − height[i]; total 6
Blue dashed blocks are water. Each column holds water up to the lower of the tallest walls on its left and right. The two-pointer code gets the same total without storing those maxima: it always works on the side whose wall is lower, because that side's max is the limiting one.
trapped water

Video Explanation

NeetCode — LeetCode 42