150 XP

100. Trapping rain water

Expert two pointers

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

Inputheights = [3, 0, 2, 0, 4]
Output7
Explanation3 + 1 + 3: everything rises to level 3.

Example 2

Inputheights = [2, 0, 2]
Output2
ExplanationThe dip holds 2 units.

Example 3

Inputheights = [1, 2, 3]
Output0
ExplanationOnly rising: the water runs off the left.

Constraints

  • heights has 0 to 1000 whole numbers, each from 0 to 10^4.

Submit also runs 10 more tests you can't see.

Code
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