Trapping Rain Water
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.
Examples
height = [0,1,0,2,1,0,1,3,2,1,2,1]6height = [4,2,0,3,2,5]9Constraints
n == height.length1 <= n <= 2 * 10^40 <= height[i] <= 10^5
๐ก Hints
Hint 1
Water at any index depends on the min of max-left and max-right heights.
Hint 2
Use two pointers from both ends, tracking leftMax and rightMax.
Hint 3
If height[left] < height[right], process left side; otherwise process right.
Algorithm Complexity
Official asymptotic Big-O runtime and auxiliary memory analysis
Two pointers from both ends. The side with the smaller height determines the water level. Track leftMax/rightMax โ if current height is less than the max, water is trapped.
Two pointers move inward from left and right boundaries, calculating trapped water on the lower elevation in a single pass.
Requires only constant scalar variables (left, right, leftMax, rightMax) without precomputed prefix arrays.
๐ Real-World Use Cases
Estimating water pooling volume on terrain based on elevation profiles โ same min-boundary logic as this problem.
โ Premium Challenge
Trapping Rain Water is classified as a premium problem.