Neural Mastery
← Practice
Trapping Rain Waterhard

Trapping Rain Water

hard Coding Interview Patterns 20–25 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Implement Trapping Rain Water via precomputed left-max/right-max arrays -- the classic hard array problem, and the key insight (water trapped at any position depends only on the shorter of the tallest walls to its left and right) that makes an O(n)-time, O(n)-space solution possible.

Related Skills

Task

Implement trap_rain_water(height): precompute, for every position, the tallest bar to its left (inclusive) and the tallest bar to its right (inclusive). The water trapped at that position is max(0, min(left_max, right_max) - height[i]); sum this over every position.

Function Signature

trap_rain_water(height: list[int]) -> int

Examples

Example 1: Classic 12-Bar Example
Input: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output: 6
Example 2: Six-Bar Example
Input: height = [4, 2, 0, 3, 2, 5]
Output: 9

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • The water level at position i is bounded by the SHORTER of the tallest wall to its left and the tallest wall to its right -- water cannot rise above the lower of the two containing walls.
  • An empty height list traps 0 units.
Python3Saved ✓
def trap_rain_water(height: list[int]) -> int:
"""height[i] is the height of a bar at position i in an elevation
map. Return the total units of rainwater trapped between the bars
after it rains."""
# Your implementation here
pass

Case 1: Classic 12-Bar Example
Input: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Expected: 6
Case 2: Six-Bar Example
Input: height = [4, 2, 0, 3, 2, 5]
Expected: 9