24. Trapping Rain Water
hardAsked at GrabCompute how much water an elevation map traps — Grab uses this as a two-pointer optimization signal.
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. Prefix and suffix max arrays
Build leftMax[i] and rightMax[i] arrays; water at i = min(leftMax[i], rightMax[i]) - height[i].
- Time
- O(n)
- Space
- O(n)
const left = new Array(n), right = new Array(n);
left[0] = height[0];
for (let i = 1; i < n; i++) left[i] = Math.max(left[i - 1], height[i]);
// symmetric right pass, then sum up min(left[i], right[i]) - height[i]Tradeoff:
2. Two-pointer single pass
Move l/r inward; advance the side with the smaller max-so-far, accumulating trapped water.
- Time
- O(n)
- Space
- O(1)
function trap(height) {
let l = 0, r = height.length - 1, lMax = 0, rMax = 0, total = 0;
while (l < r) {
if (height[l] < height[r]) {
if (height[l] >= lMax) lMax = height[l];
else total += lMax - height[l];
l++;
} else {
if (height[r] >= rMax) rMax = height[r];
else total += rMax - height[r];
r--;
}
}
return total;
}Tradeoff:
Grab-specific tips
Grab interviewers grade whether you justify advancing the lower side — frame as buffering imbalanced ride-supply heights across a regional shard.
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 Grab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →