Skip to main content

23. Trapping Rain Water

hardAsked at Indeed

Calculate how much water is trapped between elevation bars — Indeed uses this two-pointer pattern in capacity-planning and bandwidth-allocation simulations.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given n non-negative integers representing an elevation map where each bar has width 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/suffix max arrays

Precompute left-max and right-max arrays; trapped water at each position = min(leftMax,rightMax) - height[i].

Time
O(n)
Space
O(n)
function trap(height) {
  const n = height.length;
  const left = new Array(n), right = new Array(n);
  left[0] = height[0]; right[n-1] = height[n-1];
  for (let i = 1; i < n; i++) left[i] = Math.max(left[i-1], height[i]);
  for (let i = n-2; i >= 0; i--) right[i] = Math.max(right[i+1], height[i]);
  let water = 0;
  for (let i = 0; i < n; i++) water += Math.min(left[i], right[i]) - height[i];
  return water;
}

Tradeoff:

2. Two-pointer O(1) space

Maintain left and right pointers and running max heights; move the pointer with the smaller max since it determines the water level, achieving O(1) space.

Time
O(n)
Space
O(1)
function trap(height) {
  let left = 0, right = height.length - 1;
  let leftMax = 0, rightMax = 0, 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:

Indeed-specific tips

Indeed interviewers ask this to probe two-pointer mastery; walk through why the smaller-max side is safe to process before implementing — verbal justification is as important as the code.

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 Indeed interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →