Skip to main content

24. Trapping Rain Water

hardAsked at Postman

Compute how much rain water can be trapped between bars of given heights.

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. Per-column scan

For each column compute the max bar to its left and right, water = min(L,R) - h[i].

Time
O(n^2)
Space
O(1)
for each i: scan left max, right max; add max(0, min(L,R)-h[i])

Tradeoff:

2. Two-pointer with running maxima

Move two pointers inward, always processing the side whose running max is lower since it bounds the water level.

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

Tradeoff:

Postman-specific tips

Postman expects the invariant out loud — the side with the lower running max can't trap more than that max — same kind of monotonic-bound reasoning that powers their request-throttle backoff math.

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

Practice these live with InterviewChamp.AI →