Skip to main content

23. Trapping Rain Water

hardAsked at Freshworks

Compute trapped water over an elevation histogram — Freshworks asks it to probe whether you can derive two-pointer invariants under pressure.

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. Brute force (max-left, max-right per index)

For each index, scan left for max and right for max. Water above i = min(maxL, maxR) - height[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 pointers with running max

Walk pointers l and r inward. Track maxL and maxR. The smaller side's wall is the binding constraint, so add water based on that side and advance it.

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:

Freshworks-specific tips

Freshworks will ask you to prove the two-pointer invariant — the answer is 'the smaller-walled side is bounded above by the OTHER side's max, so it's safe to compute water using only the local max on that side'.

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

Practice these live with InterviewChamp.AI →