Skip to main content

22. Trapping Rain Water

hardAsked at Autodesk

Given a histogram, compute how much rain water it can trap.

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

  • 1 <= height.length <= 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 max + suffix max arrays

Precompute leftMax and rightMax arrays, then water at i is min(leftMax[i], rightMax[i]) - height[i].

Time
O(n)
Space
O(n)
build leftMax, rightMax;
for i sum max(0, min(leftMax[i],rightMax[i])-h[i]);

Tradeoff:

2. Two-pointer running max

Maintain leftMax and rightMax inline. Whichever side has the lower running max contributes water bounded by its own running max.

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

Tradeoff:

Autodesk-specific tips

Volume-under-profile problems show up in Autodesk's hydraulic and terrain simulations, so the two-pointer accumulator is a strong signal.

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

Practice these live with InterviewChamp.AI →