Skip to main content

23. Trapping Rain Water

hardAsked at ByteDance

Compute the volume of rainwater trapped between bars of varying heights — ByteDance uses it to test two-pointer DP and bottleneck-thinking 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 can be trapped 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. Per-column max scan

For each column compute max-left and max-right by scanning the whole array each time.

Time
O(n^2)
Space
O(1)
// for each i, scan left for maxL and right for maxR; add min(maxL,maxR)-h[i]

Tradeoff:

2. Two pointers

Walk pointers in from both ends, tracking running maxLeft and maxRight. The smaller side defines trapped water and advances inward.

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

Tradeoff:

ByteDance-specific tips

ByteDance interviewers grade hard on the bottleneck argument — why the smaller side decides trapped water — because the same reasoning shows up in their video-bandwidth backpressure controller.

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

Practice these live with InterviewChamp.AI →