Two-pointer pattern: Opposite ends with boundary maxima
Water above a position is limited by the lower of its best left and right boundaries. When the left boundary is no higher than the right boundary, the left side already has a sufficient opposite boundary, so its water can be finalized without knowing future interior heights.
Step-by-step approach
- Place pointers at both ends and track
left_max and right_max. - Process the side with the smaller current boundary.
- Update that side’s maximum height.
- Add the difference between the maximum and the current bar to the answer.
- Move the processed pointer inward.
Why the algorithm is correct
When left_max ≤ right_max, the water at the left pointer is determined by left_max: a right boundary at least that high is known to exist. The algorithm safely finalizes that position. The symmetric rule applies to the right pointer, so every position contributes exactly its trapped water.
Complexity analysis
Example walkthrough
In [4, 2, 0, 3, 2, 5], the left boundary remains 4 while the pointer visits heights 2, 0, 3, and 2. Those positions contribute 2, 4, 1, and 2 units, for a total of 9.
Common mistakes
- Track the maximum boundary seen so far, not just the adjacent bar.
- Add water only after updating the boundary maximum; this keeps each contribution nonnegative.