26. Trapping Rain Water
hardAsked at UdemyCompute how much water is trapped between elevation bars — Udemy uses this two-pointer classic to test candidates' ability to reason about prefix/suffix max arrays for data-bucketing problems.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of 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
1 <= height.length <= 2 * 10^40 <= height[i] <= 10^5
Examples
Example 1
height = [0,1,0,2,1,0,1,3,2,1,2,1]6Example 2
height = [4,2,0,3,2,5]9Approaches
1. Prefix and suffix max arrays
Precompute leftMax[i] and rightMax[i] arrays; water at i = min(leftMax[i], rightMax[i]) - height[i].
- Time
- O(n)
- Space
- O(n)
function trap(height) {
const n = height.length;
const lMax = new Array(n), rMax = new Array(n);
lMax[0] = height[0]; rMax[n-1] = height[n-1];
for (let i = 1; i < n; i++) lMax[i] = Math.max(lMax[i-1], height[i]);
for (let i = n-2; i >= 0; i--) rMax[i] = Math.max(rMax[i+1], height[i]);
let water = 0;
for (let i = 0; i < n; i++) water += Math.min(lMax[i], rMax[i]) - height[i];
return water;
}Tradeoff:
2. Two-pointer O(1) space
Use left and right pointers; move the pointer with the smaller max inward, accumulating water based on the known max from that side — eliminates the auxiliary arrays entirely.
- Time
- O(n)
- Space
- O(1)
function trap(height) {
let left = 0, right = height.length - 1;
let lMax = 0, rMax = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= lMax) lMax = height[left];
else water += lMax - height[left];
left++;
} else {
if (height[right] >= rMax) rMax = height[right];
else water += rMax - height[right];
right--;
}
}
return water;
}Tradeoff:
Udemy-specific tips
Udemy asks about e-learning recommendation systems, content search, and marketplace algorithms — balanced mix of arrays, hash maps, and dynamic programming problems.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Trapping Rain Water and other Udemy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →