Skip to main content

25. Trapping Rain Water

hardAsked at Yelp

Compute how much water can be trapped between elevation bars — Yelp uses the two-pointer max-tracking solution to test whether candidates can compress prefix/suffix max into one pass for recommendation-score smoothing.

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 is able to 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

At each index, water held is min(maxLeft, maxRight) - height[i]; precompute both arrays.

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

Tradeoff:

2. Two pointers

Walk from both ends; whichever side has the smaller running max determines water at that position, so advance that pointer.

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

Tradeoff:

Yelp-specific tips

Yelp will pivot to recommendation work — be ready to discuss how a two-pointer max sweep smooths spiky review-score arrays before they feed into a business-recommendation ranking model.

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

Practice these live with InterviewChamp.AI →