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 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 units 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 level is 3: 2 units over the 1, 3 over the 0, 1 over the 2. The later 1 sits between the 5 and a 2, so it holds 1. That makes 7.
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 #1

Test #2

Test #3

Argument

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

Expected Output

7