LeetCode
Trapping Rain Water
HardTwo Pointers & ArraysDay 3
Problem Statement
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 (Test Cases & Output)
Example 1:
Input:
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]Output:
6Explanation: The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water are being trapped.
Example 2:
Input:
height = [4, 2, 0, 3, 2, 5]Output:
9Constraints
- n == height.length
- 1 <= n <= 2 * 10^4
- 0 <= height[i] <= 10^5
Target Complexities
Optimal TimeO(N)
Optimal SpaceO(1)
Core Algorithmic Insight:
The two-pointer technique achieves optimal O(N) time and O(1) space by leveraging the invariant that the lower boundary dictates the fill height regardless of how high the opposite boundary is.
Font:Hack
Active Mode:Optimal Solution
Time: O(N)•Space: O(1)
Loading VS Code Hack Editor...
How This Code Works:
Two Pointers converging from left=0 and right=n-1 with variables leftMax and rightMax. Since the smaller wall always determines the trapped water limit, we process the side with smaller max and move inward. This eliminates the need for auxiliary prefix/suffix arrays, saving O(N) memory!