843. Total water trapped between bars
You get a skyline of bars of width 1. After rain, water collects in the dips between taller bars. This is a classic test of whether you can turn a per-position rule into a single linear pass.
Write trapped_water(heights). heights is a list of non-negative integers. Return the total units of water held above the bars. Water above a position rises to the smaller of the tallest bar on its left and the tallest bar on its right, minus its own height, and never below zero.
def trapped_water(heights)Example 1
Input: trapped_water([0, 2, 0, 1, 0, 3])
Output: 5
Example 2
Input: trapped_water([3, 2, 1])
Output: 0
Constraints
- 0 <=
len(heights)<= 100,000 - 0 <=
heights[i]<= 100,000
Hint 1
Write the per-position formula first.
Hint 2
Try prefix and suffix maximum arrays.
Hint 3
Then ask which side's maximum is the binding one.
Common mistakes
- Using only the nearest taller bar instead of the tallest one.
- Letting water go negative at peaks.
- Off-by-one when the pointers meet.
Understand the idea
Many array puzzles reduce to a per-index formula built from a prefix and a suffix statistic. For [0, 2, 0, 1, 0, 3], the left maxima are 0, 2, 2, 2, 2, 3 and the right maxima are 3, 3, 3, 3, 3, 3, so the water is 0 + 0 + 2 + 1 + 2 + 0 = 5. Two pointers compute the same thing in one pass with O(1) memory.