Trapping Rain Water
Given bar heights, compute how much rain water the bars trap.
Open on LeetCode ↗Intuition
Water above any bar is min(tallest-to-left, tallest-to-right) − height. The side with the smaller wall decides the level, so walk two pointers inward from the ends: whichever side is lower is fully determined by its own max — the other side is guaranteed at least as tall.
Approach
Per-bar formula
Column i holds min(maxLeft, maxRight) − h[i] water (never negative). Precomputing both max arrays gives an easy O(n)/O(n) solution.
Drop the arrays with two pointers
Keep leftMax and rightMax while pointers close in. If leftMax ≤ rightMax, the left bar's water is leftMax − h[l] — the right side can't be the binding wall. Move that pointer.
Sum as you go
Each step settles exactly one column. O(n) time, O(1) space.
Solution & live demo
Edge cases
Smaller wall is always the current bar itself — every contribution is 0.
No basin can form; loop yields 0.