Skip to main content

24. Trapping Rain Water

hardAsked at Coinbase

Calculate total liquidity trapped between price-bar barriers — Coinbase uses this classic to evaluate whether engineers can reason about prefix/suffix maximums and then collapse the solution to a two-pointer scan without extra arrays.

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

Explanation: 6 units of water are trapped between the bars.

Example 2

Input
height = [4,2,0,3,2,5]
Output
9

Approaches

1. Prefix/suffix max arrays

Precompute leftMax[i] and rightMax[i]. Water at each bar = min(leftMax[i], rightMax[i]) - height[i].

Time
O(n)
Space
O(n)
function trap(height) {
  const n = height.length;
  const leftMax = new Array(n).fill(0);
  const rightMax = new Array(n).fill(0);
  leftMax[0] = height[0];
  for (let i = 1; i < n; i++) leftMax[i] = Math.max(leftMax[i - 1], height[i]);
  rightMax[n - 1] = height[n - 1];
  for (let i = n - 2; i >= 0; i--) rightMax[i] = Math.max(rightMax[i + 1], height[i]);
  let water = 0;
  for (let i = 0; i < n; i++) water += Math.min(leftMax[i], rightMax[i]) - height[i];
  return water;
}

Tradeoff:

2. Two-pointer (optimal)

Advance the pointer on the shorter-max side, accumulating water. Eliminates the extra arrays by computing max on the fly.

Time
O(n)
Space
O(1)
function trap(height) {
  let left = 0, right = height.length - 1;
  let leftMax = 0, rightMax = 0, water = 0;
  while (left < right) {
    if (height[left] < height[right]) {
      if (height[left] >= leftMax) leftMax = height[left];
      else water += leftMax - height[left];
      left++;
    } else {
      if (height[right] >= rightMax) rightMax = height[right];
      else water += rightMax - height[right];
      right--;
    }
  }
  return water;
}

Tradeoff:

Coinbase-specific tips

Coinbase treats this as a liquidity-depth question: given a histogram of bid/ask volumes, how much liquidity is 'locked' between walls? They test whether you arrive at the two-pointer solution — constant space matters on their high-frequency data paths. Expect a follow-up asking you to prove why advancing the shorter side is always safe.

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

Practice these live with InterviewChamp.AI →