Skip to main content

26. Trapping Rain Water

hardAsked at Quora

Calculate how much water collects between elevation bars — Quora uses this two-pointer constraint pattern in their feed-ranking logic to model how much engagement 'pools' between dominant signals in a user's interest profile.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given n non-negative integers representing an elevation map where each bar has width 1, compute how much water can be trapped 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. Precompute left/right max arrays

For each index, water trapped = min(maxLeft[i], maxRight[i]) - height[i]. Two auxiliary passes, then one linear scan.

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 O(1) space

Track leftMax and rightMax with two inward-moving pointers. The side with the smaller max determines how much water accumulates at that pointer; advance that side. Constant extra space.

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

Tradeoff:

Quora-specific tips

Quora rates this problem on your ability to derive the two-pointer approach from first principles — they want to see you prove to yourself why it's correct, not just recall the pattern. Walk through the invariant: 'whichever side has the smaller max, the water at that position is fully determined.' That's the reasoning they care about.

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

Practice these live with InterviewChamp.AI →