Menu
CoddyTech

Trapping Rain Water

A row of bars stands side by side, each one unit wide: height[i] is the height of bar i. Rain falls on the row and collects in the dips between bars. Water stays above a bar only if a taller bar stands somewhere to its left and somewhere to its right; past the first and the last bar it runs off.

Return the total number of unit squares of water the row holds.

Function

trap(height: integer-array) → integer
heightinteger-array
the height of each bar, from left to right
Returnsinteger
the total units of trapped water

Constraints

  • 1 ≤ height.length ≤ 2 × 104
  • 0 ≤ height[i] ≤ 105
  • Every bar is one unit wide, and water does not stay past the first or the last bar.

Examples

Input
height = [0, 3, 1, 0, 2, 5, 1, 2]
Output
7
Explanation
Between the 3 and the 5 the water rises to level 3: it holds 2 units over the bar of 1, 3 over the 0 and 1 over the 2. The 1 near the end sits between the 5 and a 2, so its level is 2 and it holds 1 unit. 2 + 3 + 1 + 1 = 7.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

Suppose the bars form a 2D grid of heights and water can escape in all four directions. How would you count the trapped water then?

Reset code
def trap(height):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

height = [0, 3, 1, 0, 2, 5, 1, 2]

Expected

7