Trapping Rain Water – Solution & Complexity
1. Understand What Water Needs
- Water above an index is limited by the tallest wall on its left and the tallest wall on its right.
- If the shorter of those two walls is taller than the current bar, the difference is trapped water.
- Bars at the ends cannot trap water because one side is open.
2. Start with Prefix and Suffix Maximums
- A direct dynamic programming solution precomputes
left_max[i]andright_max[i]. - Then each index contributes
min(left_max[i], right_max[i]) - height[i]if that value is positive. - This is correct but uses O(n) extra space.
3. Use the Two-Pointer Insight
- We can avoid the extra arrays by scanning from both ends.
- Whichever side has the smaller current maximum is the limiting side for that step.
- If
left_max <= right_max, the left position's water is already determined; otherwise the right position's water is determined.
4. Accumulate Water While Moving Inward
- Keep
left,right,left_max, andright_max. - Update the maximum for the side you move.
- If the current bar is lower than that side's maximum, add the difference to the answer.
5. Final Complete Solution
- This version handles empty or very small arrays naturally because the loop does not run.
- Each bar is visited at most once.
- Time complexity is O(n), and extra space complexity is O(1).