Sign inEnroll free
DSA Visualizer · 25 visualizationsTrapping Rain Water
HardTwo Pointers

Trapping Rain Water

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.

The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n) · space O(1)
def trap(height: list[int]) -> int:
    l, r = 0, len(height) - 1
    maxL, maxR = height[l], height[r]
    water = 0
    while l < r:
        if maxL <= maxR:
            l += 1
            maxL = max(maxL, height[l])
            water += maxL - height[l]
        else:
            r -= 1
            maxR = max(maxR, height[r])
            water += maxR - height[r]
    return water
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough