Trapping Rain Water

Advanced

Let's imagine each position on a list as a container, where the integers in the list represent the height of walls. Your mission is to determine how much rainwater would be trapped between these walls after a rainstorm.

For example, given the list [0, 2, 0, 3, 0, 4, 0, 3, 0, 2, 0], your function should return 12. Here's why:

  • Between the second wall of height 2 and the fourth wall of height 3, it can trap 2 units of water (so the scenario is [2, 0, 0, 3]).
  • Between the fourth wall of height 3 and the sixth wall of height 4, it can trap 3 units (scenario [3, 0, 4]).
  • Between the sixth wall of height 4 and eighth wall of height 3, it can trap 3 units (scenario [4, 0, 3]).
  • Between the eighth wall of height 3 and tenth wall of height 2, it can trap 2 units (scenario [3, 0, 2]).
  • And finally, the last wall can trap 2 units with the zero wall at the end (scenario [2, 0]).

This is how the rainwater gets trapped! Now it's your turn to make the magic happen by creating a function that calculates the trapped rainwater.

Examples

Let's see it in action:

calculate_trapped_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) # Output: 6 calculate_trapped_water([0, 0, 0, 0]) # Output: 0 calculate_trapped_water([3, 0, 2, 0, 4]) # Output: 7

Happy coding and may the rain always fill your containers!

Geek
Inputs

Arg 1:

[0,1,0,2,1,0,1,3,2,1,2,1]
Expected Output
6
Actual Output