Back to Practice
#0291

Trapping Rain Water

HardDSA40 min25 XP

Problem

Given non-negative bar heights, return how many units of water can be trapped after raining.

Why This Matters

This is a classic two-pointer proof problem where the lower boundary determines safe progress.

Function Signature

def trap_rain_water(height):

Examples

Example 1
Inputheight = [0,1,0,2,1,0,1,3,2,1,2,1]
Output6

The dips between taller bars hold 6 total units of water.

Constraints

  • Return the exact requested value.
  • Handle edge cases cleanly.
  • Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Classic terrain
Input[0,1,0,2,1,0,1,3,2,1,2,1]
Expected6

Water accumulates in multiple valleys.

No trap
Input[1,2,3]
Expected0

There is no right wall for earlier bars.

Hidden Test Categories
empty inputflat barssingle valley