hardStackTwo PointersTwo Pointers

Trapping Rain Water

hardTime: O(n)Space: O(1)

Signals to notice

trapped water between barswater level at each positionbounded by shorter side

Brute force first

For each position, find the max height to its left and right. Re-scans the array for every position. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Two pointers from both ends converging inward. Water at any position = min(maxLeft, maxRight) - height. Move the pointer with the smaller max — you know the water level is bounded by the smaller side. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

Water at position i = min(maxLeft, maxRight) - height[i]. If maxLeft < maxRight, the water level at the left pointer is determined by maxLeft regardless of what's further right — so you can safely compute it and move inward. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Not understanding WHY you move the smaller side — if maxLeft < maxRight, no bar to the right can make the left pointer's water level higher. It's bounded by maxLeft, period. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Two Pointers Pattern