Trapping Rain Water

Hard
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Trapping Rain Water

Approach

Use two pointers from both ends, tracking the maximum height seen from each side. Process the pointer with the smaller max height: if the current bar is shorter than its side max, the difference is trapped water. Otherwise, update the side max. Move the processed pointer inward.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Two Pointers (Converging)

Why It Works

Water at any position is determined by min(leftMax, rightMax) - height. By always processing the side with the smaller max, we know the other side has a taller or equal wall, so the water level is determined solely by the current side max.

Updated Feb 2026