Trapping Rain Water

HardAcc. 48.2%
+100 XP 50

The Final Elevation Challenge

Water at index i is trapped by min(leftMax, rightMax) - height[i].

The Assignment

Your function receives height.

  1. Use Two Pointers (left=0, right=end).
  2. Track leftMax and rightMax.
  3. Move the pointer with the smaller max inwards.
  4. Add difference to totalWater.
  5. Print the result.

01EXAMPLE 1

Input[0,1,0,2,1,0,1,3,2,1,2,1]
Output6

Explanation: Total 6 units of water trapped.

Constraints

  • O(n) time and O(1) space.
ArraysTwo Pointers
JavaScript
Loading...
1 Hidden

Input Arguments

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

Expected Output

6

Click RUN to test your solution