Rain on Brick Towers

Hardtwo pointersAlso known as Trapping Rain Water

A child builds a row of toy-brick towers on the garden table, each one brick wide, standing right next to each other. The heights, in bricks, are something like [2, 0, 3, 1, 0, 2]. Then it rains.

Water collects in the dips between taller towers and spills off where there is nothing to hold it. Looking at the row from the front, each one-brick square of water counts as one unit. How many units of water does the row hold once the rain stops?

Your task

Write trappedWater(heights). heights[i] is the height of tower i. Every tower is 1 unit wide and there are no gaps between them. Water spills off both ends of the row. Return the total units of water held.

Above tower i, water rises to the lower of two levels: the tallest tower anywhere to its left (including itself) and the tallest tower anywhere to its right (including itself). The water above it is that level minus heights[i].

trappedWater(heights: int[]) → int

Examples

Example 1
Input
heights = [2, 0, 3, 1, 0, 2]
Output
5
Why

Tower 1 sits between walls of 2 and 3, so water rises to 2: 2 units. Towers 3 and 4 have 3 on the left and 2 on the right, so water rises to 2: 1 unit above tower 3 and 2 above tower 4. Total 2 + 1 + 2 = 5.

Example 2
Input
heights = [4, 1, 1, 0, 3]
Output
7
Why

The right wall is 3, lower than the left wall of 4, so water rises to 3 between them: 2 + 2 + 3 = 7. Looking only at each tower's direct neighbours would miss most of this water.

Constraints

  • 0 ≤ heights.length ≤ 10,000
  • 0 ≤ heights[i] ≤ 100,000
Start with brute force

For every tower, scan everything to its left for the tallest tower, scan everything to its right for the tallest, and add min(leftTallest, rightTallest) - height.

Each tower triggers two scans of up to n towers, so 10,000 towers cost about 100 million steps. The scans repeat almost the same work for neighbouring towers: the tallest tower to the left of tower 501 is nearly always the one you found for tower 500.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code