Trapping Rain Water
You're given n non-negative integers describing an elevation map, where each value is the height of a bar one unit wide. After rain falls, figure out how much water ends up trapped between the bars.
Input Format
Implement trap(height). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
height = [0,1,0,2,1,0,1,3,2,1,2,1] Output
6 Example 2
Input
height = [4,2,0,3,2,5] Output
9 Constraints
- 1 <= n <= 2 * 10^4
- 0 <= height[i] <= 10^5
Test Cases (2)
Case 1
Args: [[0,1,0,2,1,0,1,3,2,1,2,1]]
Expected: 6
Case 2
Args: [[4,2,0,3,2,5]]
Expected: 9
Two Pointers
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left];
left++;
} else {
rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right];
right--;
}
}
return water;
}Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.