Rain between the rocks
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- lists
- loops
- comparisons
Problem
The storm has passed, and puddles are left between the rocks on the shore. The rocks stand in a row, each one is one unit wide, and the list holds their heights (whole numbers from 0 up; it may be empty).
Above each rock the water rises to the lower of two heights: the tallest rock to its left and the tallest rock to its right. Whatever is above the rock is water; if that height is not above the rock, there is none there. The first and last rocks never hold water: they are missing a side.
With [3, 0, 2, 0, 4], the tallest to the left of the middle rocks is 3 and to the right is 4, so the water reaches 3. The first 0 holds 3, the 2 holds 1 and the other 0 holds 3: you return 7.
Return the total water as a whole number. With no rocks, or one or two, it is 0.
Examples
The example
[3, 0, 2, 0, 4] → 7
A long shore
[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] → 6
The rocks only go up
[1, 2, 3, 4] → 0
The right side is the lower one
[4, 0, 1] → 1
A single rock
[5] → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def trapped_water(rocks):
passJavaScript
function trappedWater(rocks) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.