Overview
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.
Constraints
n == height.length1 <= n <= 20,0000 <= height[i] <= 100,000
Examples
trap([0,1,0,2,1,0,1,3,2,1,2,1]); // => 6 trap([4,2,0,3,2,5]); // => 9
Solution
Reveal solution
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;
}Two-pointer approach: move the smaller side inward, accumulating water based on the running max.
Resources
trapping-rain-water.js
Trapping Rain Water
hardcodingAlgorithmsArrays
Overview
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.
Constraints
n == height.length1 <= n <= 20,0000 <= height[i] <= 100,000
Examples
trap([0,1,0,2,1,0,1,3,2,1,2,1]); // => 6 trap([4,2,0,3,2,5]); // => 9
Solution
Reveal solution
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;
}Two-pointer approach: move the smaller side inward, accumulating water based on the running max.
Resources
NameTopicDifficulty
103 of 103 problems