Array techniquesAnimated
Trapping Rain Water
Water above a bar = min(left max, right max) − height; two pointers compute it.
Time
O(n)
Extra space
O(1)
Use it for
Classic two-pointer interview problem.
How it works
- Water sits above a bar up to the lower of the tallest bars on its left and right, minus the bar itself.
- Use two pointers from both ends and the tallest bar seen on each side so far.
- Always process the side with the smaller maximum: its water level is already decided by that smaller wall.
- Add up the water for every bar.
Watch it run
Loading animation…