100. Trapping rain water
A row of walls stands side by side, each 1 unit wide; heights[i] is the height of wall i. When it rains, water
collects in the dips between taller walls. Water over a wall rises to the level of the lower of two walls: the
highest one anywhere to its left and the highest one anywhere to its right. Above that it would spill over.
Write a function trapped_water(heights) that returns how many units of water the row holds in all.
- Water can't stay over the first or the last wall: it spills off the ends.
- Fewer than three walls hold no water.
For each wall, finding the highest wall on each side separately takes n steps, n * n in all. Two pointers moving in from both ends can settle one wall at each step, with no extra lists.
Example 1
heights = [3, 0, 2, 0, 4]7Example 2
heights = [2, 0, 2]2Example 3
heights = [1, 2, 3]0Constraints
heightshas 0 to 1000 whole numbers, each from 0 to 10^4.
Submit also runs 10 more tests you can't see.
- The water over wall
iismin(highest to its left, highest to its right) - heights[i], counting the wall itself in both (so never below 0). - Keep two pointers,
iat the left end andjat the right, with the highest wall seen so far from each side. - Move the pointer on the lower side. That side's highest is the lower of the two limits, since the other side already has a wall at least as high, so its water can be added at once.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def trapped_water(heights):
"""Work out how much water the walls hold.
heights: list of int, the walls' heights in a row
Returns: int, the total units of water held
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.