Skip to main content

24. Trapping Rain Water

hardAsked at Grab

Compute 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.length
  • 1 <= n <= 2 * 10^4
  • 0 <= height[i] <= 10^5

Examples

Example 1

Input
height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output
6

Example 2

Input
height = [4,2,0,3,2,5]
Output
9

Approaches

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.

Output

Press Run or Cmd+Enter to execute

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 →