Skip to content

visual walkthrough

Trapping Rain Water

HardOpposite EndsReported at: AmazonMetaMicrosoft+12

The most famous two-pointer Hard; also solvable with prefix maxima or a stack.

Solve on LeetCode

The idea

Water sits above a bar up to the height of the shorter of the two tallest walls on either side. Computing both maxima for every bar is slow.

With two pointers you don't need both: whichever end is currently shorter has a taller wall somewhere on the other side, so its own side's max is the limit and its water can be settled immediately.

Complexity

approachtimespace
Look left and rightO(n²)O(1)
Two pointersO(n)O(1)

More walkthroughs