28. Trapping Rain Water
hardAsked at BookingCalculate total water trapped between elevation bars — Booking's data team uses an analogous two-pointer capacity calculation when computing the maximum available inventory across a price-bucket histogram for dynamic pricing.
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 level = min(maxLeft[i], maxRight[i]) - height[i]. Two passes to build the arrays, one pass to sum.
- Time
- O(n)
- Space
- O(n)
function trap(height) {
const n = height.length;
const leftMax = new Array(n).fill(0);
const rightMax = new Array(n).fill(0);
leftMax[0] = height[0];
for (let i = 1; i < n; i++) leftMax[i] = Math.max(leftMax[i - 1], height[i]);
rightMax[n - 1] = height[n - 1];
for (let i = n - 2; i >= 0; i--) rightMax[i] = Math.max(rightMax[i + 1], height[i]);
let water = 0;
for (let i = 0; i < n; i++) {
water += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return water;
}Tradeoff:
2. Two pointers (O(1) space)
Move the pointer on the shorter side inward; the water above it is determined by that side's max. One pass, no extra arrays.
- Time
- O(n)
- Space
- O(1)
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let 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;
}Tradeoff:
Booking-specific tips
Booking's capacity planning team thinks in histograms — frame your answer in terms of 'bounded volume between walls'. The two-pointer O(1) approach always impresses; be prepared to prove correctness by explaining why the shorter side's water level is fully determined.
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 Booking interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →