← Back to DSA Animator
Trapping Rain Water LC #42 Hard Two Pointers
Approach
Two Pointer with Running Max
Track maxLeft and maxRight. Process side with smaller max — water = max − height. O(n) time, O(1) space.
■ Left pointer ■ Right pointer ■ Trapped water ■ Wall
L
R
maxL
maxR
water
0
Press Play to start
💧
Total trapped water
Algorithm
1
L=0, R=n-1, maxL=0, maxR=0, water=0
2
If maxL ≤ maxR: process left side
3
maxL=max(maxL,h[L]); water+=maxL-h[L]; L++
4
Else: maxR=max(maxR,h[R]); water+=maxR-h[R]; R--
Time
O(n)
Space
O(1)
Why It Works

Water at index i = min(maxLeft[i], maxRight[i]) − height[i].

When maxL ≤ maxR, the left pointer's limiting boundary is definitely maxL (right wall is taller), so water = maxL − h[L].

We don't need to know the actual min — the smaller side's max IS the bottleneck.