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, side by side. 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 nothing holds it. Seen from the front, each one-brick square of water is one unit. How many units does the row hold?

Your task

Write trappedWater(heights). heights[i] is the height of tower i. Every tower is 1 unit wide, with 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 to its left (including itself) and the tallest tower 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, which holds 2 units. Towers 3 and 4 have a 3 on the left and a 2 on the right, so water rises to 2 there as well, giving 1 unit above tower 3 and 2 above tower 4. The total is 2 + 1 + 2 = 5.

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

The right wall, 3, is lower than the left wall, 4, so water rises to 3 between them, and the three towers in between hold 2 + 2 + 3 = 7. Looking only at direct neighbours would miss most of it.

Constraints

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

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

That is two scans of up to n towers each, so 10,000 towers cost about 100 million steps. Neighbouring towers repeat almost the same work: the tallest tower left of tower 501 is nearly always the one 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