Given bar heights of width 1, return how much water they trap after raining.
Before you code
Water above a bar is min(tallest on the left, tallest on the right) - height. Precomputing both maximums is O(n) space; two pointers avoid it.
Hints
- Keep
left_maxandright_maxas the pointers move inward. - If
left_max <= right_max, the left bar's water is decided byleft_max: add it and move left. Otherwise do the same on the right. - Alternative: a monotonic stack that fills water layer by layer.
Production & complexity notes
When solving Trapping rain water on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Two pointers to reinforce the underlying pattern.
What it practices
Moving the side whose bound is already known, from Two pointers.