23. Trapping Rain Water
hardAsked at DigitalOceanCalculate the total water trapped by an elevation map — a classic hard problem DigitalOcean uses to probe two-pointer mastery and capacity planning thinking.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
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 <= 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. Precompute left/right max arrays
For each index, water = min(leftMax[i], rightMax[i]) - height[i]. O(n) time, O(n) space for two extra arrays.
- 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
Maintain left and right pointers and track leftMax/rightMax. The side with the smaller max is the bottleneck — add water from that side and advance the pointer inward.
- Time
- O(n)
- Space
- O(1)
function trap(height) {
let lo=0, hi=height.length-1;
let leftMax=0, rightMax=0, water=0;
while(lo<hi){
if(height[lo]<height[hi]){
height[lo]>=leftMax ? leftMax=height[lo] : water+=leftMax-height[lo];
lo++;
} else {
height[hi]>=rightMax ? rightMax=height[hi] : water+=rightMax-height[hi];
hi--;
}
}
return water;
}Tradeoff:
DigitalOcean-specific tips
DigitalOcean uses this problem to assess capacity-planning intuition — interviewers appreciate framing the 'bottleneck side' insight in terms of network throughput constraints.
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 DigitalOcean interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →