25. Trapping Rain Water
hardAsked at TeslaCalculate how much water a histogram traps after rain — Tesla's thermal management team uses a structurally identical algorithm to model coolant pooling in battery-pack channel geometries, identifying where fluid accumulates before designing drainage paths.
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]6Explanation: The elevation map traps 6 units of water (visualize the gaps between bars).
Example 2
height = [4,2,0,3,2,5]9Approaches
1. Precompute left/right max arrays
Build leftMax[i] and rightMax[i] arrays. Water at position i = min(leftMax[i], rightMax[i]) - height[i]. Two extra O(n) arrays.
- 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-pointer O(1) space
Maintain left/right pointers and running max on each side. Whichever side has the smaller max, compute its water contribution and advance that pointer inward.
- 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]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
water += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
water += rightMax - height[right];
}
right--;
}
}
return water;
}Tradeoff:
Tesla-specific tips
Tesla asks this in hardware-adjacent roles because the thermal and structural simulation teams think in exactly these terms. The two-pointer solution is the expected answer at the senior level — derive it by explaining why you can commit to a water value on the side with the smaller max (the other side is guaranteed to be at least as tall). Many candidates stumble on why it's safe to advance; proving that invariant out loud is what separates a strong pass from a borderline one.
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 Tesla interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →