Skip to main content

23. Trapping Rain Water

hardAsked at Electronic Arts

Calculate how much water can be trapped between bars of varying heights, a spatial simulation problem EA asks to test terrain modeling and two-pointer mastery.

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. Precompute left/right max arrays

For each position, the water is min(leftMax, rightMax) - height. Precompute both maxima arrays in two passes.

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

Tradeoff:

2. Two pointers O(1) space

Use two pointers converging inward, tracking running left and right maxima. Process the shorter side at each step — water there is determined by the shorter boundary. This O(1) space approach is the gold-standard EA solution.

Time
O(n)
Space
O(1)
function trap(height) {
  let lo = 0, hi = height.length - 1;
  let lMax = 0, rMax = 0, water = 0;
  while (lo < hi) {
    if (height[lo] <= height[hi]) {
      if (height[lo] >= lMax) lMax = height[lo];
      else water += lMax - height[lo];
      lo++;
    } else {
      if (height[hi] >= rMax) rMax = height[hi];
      else water += rMax - height[hi];
      hi--;
    }
  }
  return water;
}

Tradeoff:

Electronic Arts-specific tips

EA interviews cover game development data structures, pathfinding (A*, BFS on grids), spatial algorithms, and simulation problems. Grid/matrix manipulation and BFS on 2D arrays are very common.

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

Practice these live with InterviewChamp.AI →