Skip to content
StackDecode
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

  1. Water sits above a bar up to the lower of the tallest bars on its left and right, minus the bar itself.
  2. Use two pointers from both ends and the tallest bar seen on each side so far.
  3. Always process the side with the smaller maximum: its water level is already decided by that smaller wall.
  4. Add up the water for every bar.

Watch it run

Loading animation…