Problem
Problem page: https://leetcode.com/problems/trapping-rain-water/
Topics: Array, Stack, Two Pointers
Difficulty: Hard
Similar problems: (M) Container With Most Water, (M) Product of Array Except Self
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given[0,1,0,2,1,0,1,3,2,1,2,1], return6.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. **Thanks Marcos** for contributing this image!
Analysis
Think of the numbers in a sequence as the heights of walls that hold back water, and find the most water those walls can hold in total. The picture in the problem makes this clear at a glance, so there's no need to say much more.
At any given point x, the amount of water it holds should depend on the lower of two walls: the tallest wall to its left and the tallest wall to its right. Take A=[0,1,0,2,1,0,1,3,2,1,2,1] for example. At A[4]=1, the tallest wall to the left is A[3]=2 and the tallest wall to the right is A[7]=3. The lower of the two is A[3]=2, so the water depth at A[4] is A[3]-A[4]=1, and multiplying that by the base width of 1 gives 1 unit of water.
It doesn't make sense to look for this minimum separately for each point, since that would give us a time complexity of O(n*n). Allocate an array max_heights of the same length as the original array A to record the most water each point can hold. First go through A from left to right, keeping track of the largest value seen so far and writing it into max_heights at each point. Start at the right end of A and work back to the left with a fresh running maximum. If the running maximum from the right is smaller than the corresponding value in max_heights, write the running maximum into that position. This way, two passes with a time complexity of O(n) each give us the amount of water each point can hold. Then go through max_heights. Add up the differences wherever max_heights exceeds A at the same position to get the total amount of water held. If a value in A is greater than the corresponding value in max_heights, that point can't hold any water.
The space complexity is O(n) and the time complexity is O(n).
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-trapping-rain-water/

