Skip to main content

99. Trapping Rain Water

hardAsked at Ola

Compute how much water can be trapped between elevations.

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-index max

For each i, scan left/right for max heights and compute the water above i.

Time
O(n^2)
Space
O(1)
// brute per-index scan; too slow at 2*10^4

Tradeoff:

2. Two pointers

Track left/right pointers and running max heights; the smaller side dictates how much can be trapped at its index.

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

Tradeoff:

Ola-specific tips

Ola asks this for the elegant two-pointer reasoning; tie it to estimating absorbed-demand 'pools' that build up between supply peaks on a city skyline.

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

Practice these live with InterviewChamp.AI →