Trapping rain water
Water above one bar is min(tallest left, tallest right) − its own height. The two-pointer version exploits one fact: whichever side is shorter is the binding constraint, so that side's water can be settled immediately. One pass, O(1) space.
Overview
The per-bar formula
Water sits above a bar up to the level of the lower of the two walls containing it: min(max to the left, max to the right) − height, or zero if that is negative.
The direct implementation precomputes both arrays of running maxima and then sums. That is O(n) time and O(n) space, perfectly correct, and the right first answer. The two-pointer version removes the arrays.
Step through it
What to watch
- Only the shorter side is advanced, and only that side's water is settled.
- The running maxima are two integers, not two arrays.
- Each bar is visited exactly once.
Say this out loud
"Per bar it's min of the max to the left and the max to the right, minus its height. Two pointers from both ends: always move the shorter side, because that side's maximum is what limits it. O(n) time, O(1) space."