Skip to main content

25. Trapping Rain Water

hardAsked at Wise

Compute trapped water given an elevation map — Wise reframes it as the locked-up liquidity between two FX pool walls.

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. Per-index left and right max

For each index, scan left and right for the max height; water at i is min(maxL, maxR) - h[i].

Time
O(n^2)
Space
O(1)
let total=0;
for (let i=0;i<height.length;i++){
  let l=0,r=0;
  for (let j=0;j<=i;j++) l=Math.max(l,height[j]);
  for (let j=i;j<height.length;j++) r=Math.max(r,height[j]);
  total += Math.min(l,r)-height[i];
}
return total;

Tradeoff:

2. Two-pointer with running walls

Two pointers converge; each step the smaller side dictates the trapped amount against its running max, and that pointer advances.

Time
O(n)
Space
O(1)
function trap(height){
  let l = 0, r = height.length - 1;
  let maxL = 0, maxR = 0, total = 0;
  while (l < r){
    if (height[l] < height[r]){
      if (height[l] >= maxL) maxL = height[l];
      else total += maxL - height[l];
      l++;
    } else {
      if (height[r] >= maxR) maxR = height[r];
      else total += maxR - height[r];
      r--;
    }
  }
  return total;
}

Tradeoff:

Wise-specific tips

Wise grades whether you reach for the converging two-pointer pattern — their cross-border liquidity scanner uses the same shape to compute pooled balance between two FX walls.

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

Practice these live with InterviewChamp.AI →