Skip to main content

25. Trapping Rain Water

hardAsked at Coupang

Compute how much rainwater is trapped between bars, mirroring how Coupang's returns-processing pipeline estimates buffer capacity between fulfillment-center bottlenecks during peak-event throughput.

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

Problem

Given n non-negative integers representing an elevation map where each bar has unit width, compute how much water it can trap after raining.

Constraints

  • 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 i, water = min(leftMax[i], rightMax[i]) - height[i]. Build the two arrays in linear time.

Time
O(n)
Space
O(n)
const leftMax = [], rightMax = [];
leftMax[0] = height[0]; for (let i=1;i<n;i++) leftMax[i] = Math.max(leftMax[i-1], height[i]);
rightMax[n-1] = height[n-1]; for (let i=n-2;i>=0;i--) rightMax[i] = Math.max(rightMax[i+1], height[i]);
let total = 0; for (let i=0;i<n;i++) total += Math.min(leftMax[i], rightMax[i]) - height[i];
return total;

Tradeoff:

2. Two pointers

Walk from both ends. Whichever side has the smaller running max is the bottleneck for that index; accumulate water there and advance.

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

Tradeoff:

Coupang-specific tips

Coupang's returns-processing pipeline estimates buffer capacity between fulfillment-center bottlenecks during peak-event throughput; the two-pointer O(1)-space approach is the canonical pattern in their backpressure-modeling 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 Coupang interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →