Trapping rain water
A row of bars stands on flat ground, side by side with no gaps. Bar i is 1 unit wide and heights[i] units tall; a height of 0 is bare ground. It rains until every spot that can hold water is full. Water cannot pass through a bar, it spreads sideways freely, and any water that reaches either end of the row runs off.
Return the total amount of water left standing on the row, in units, where one unit fills a 1 by 1 square.
heights = [3, 0, 2, 0, 4]Output7The water level is 3, set by the left bar. Water stands 3 deep over position 1, 1 deep over position 2 and 3 deep over position 3: 3 + 1 + 3 = 7.
heights = [0, 2, 0, 0, 1]Output2The right wall is only 1 tall, so water stands 1 deep over positions 2 and 3. Position 0 has no wall on its left, so water there runs off.
heights = [1, 2, 3, 2, 1]Output0A hill holds nothing: all the water runs off both sides.
0 ≤ len(heights) ≤ 105
0 ≤ heights[i] ≤ 105
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.