Skip to main content

24. Trapping Rain Water

hardAsked at Coursera

Compute how much rainwater can be trapped between elevation bars, a two-pointer hard problem Coursera asks to gauge O(n) space-optimized reasoning.

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 index, store the max height to its left and right; trapped water = min(leftMax, rightMax) - height[i]. O(n) time and O(n) space.

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)

Move left and right pointers inward; whichever side has the smaller max determines the water at that position. This eliminates the precomputed arrays and achieves O(1) extra space.

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

Tradeoff:

Coursera-specific tips

Coursera interviews emphasize algorithms for educational platforms, content recommendation systems, and scalable delivery pipelines. Medium-difficulty graph and DP problems are typical.

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

Practice these live with InterviewChamp.AI →