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
2and the fourth wall of height3, it can trap2units of water (so the scenario is[2, 0, 0, 3]). - Between the fourth wall of height
3and the sixth wall of height4, it can trap3units (scenario[3, 0, 4]). - Between the sixth wall of height
4and eighth wall of height3, it can trap3units (scenario[4, 0, 3]). - Between the eighth wall of height
3and tenth wall of height2, it can trap2units (scenario[3, 0, 2]). - And finally, the last wall can trap
2units 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!
Inputs
Arg 1:
[0,1,0,2,1,0,1,3,2,1,2,1]Expected Output
6Actual Output