Skip to content

Trapping Rain Water

Topic: 02. Arrays (Two Pointers)

Link: LeetCode 42 - Trapping Rain Water

1. Logical Breakdown

  • [x] Core Logic: Water = min(LeftMax, RightMax) - Height[i].
  • [x] Optimization: Use Two Pointers to avoid O(N) space.

2. Visualization

graph LR Check["Height[L] < Height[R]?"] -- Yes --> UpdateL["Update LeftMax & Add Water"] Check -- No --> UpdateR["Update RightMax & Add Water"]

3. Complexity

  • Time: O(N)
  • Space: O(1)

4. Code

package com.dsa.arrays;

public class TrappingRainWater {
    public int solve(int[] height) {
        if (height == null || height.length == 0) return 0;

        int left = 0, right = height.length - 1;
        int leftMax = 0, rightMax = 0;
        int water = 0;

        while (left < right) {
            if (height[left] < height[right]) {
                if (height[left] >= leftMax) {
                    leftMax = height[left];
                } else {
                    water += leftMax - height[left];
                }
                left++;
            } else {
                if (height[right] >= rightMax) {
                    rightMax = height[right];
                } else {
                    water += rightMax - height[right];
                }
                right--;
            }
        }
        return water;
    }
}