Skip to content

Commit

Permalink
solution(python): 42. Trapping Rain Water
Browse files Browse the repository at this point in the history
42. Trapping Rain Water
- Python
  • Loading branch information
godkingjay authored Oct 31, 2023
2 parents 100b166 + da0de20 commit c0c4ca8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Hard/42. Trapping Rain Water/Approach 1/sol.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
1. The code first checks if the input elevation map, height, is empty. If it is, it returns 0 immediately, signifying no trapped water.
2. Two arrays, lm (left maximum) and rm (right maximum), are initialized to store the maximum heights to the left and right of each position, respectively.
3. Starting from the leftmost position of the elevation map, the code calculates and stores the maximum height to the left (including the current position) in the lm array.
4. Similarly, beginning from the rightmost position and moving leftwards, the maximum height to the right (including the current position) is calculated and stored in the rm array.
5. Leveraging the two pre-computed arrays, the trapped water at each position is calculated. This is done by determining the minimum of the left and right maximum heights for each position and subtracting the height of the current position.
6. The trapped water values for all positions are summed to yield the total trapped water.
## Time Complexity:
The **time complexity** of this approach is

**O(n)**, where n is the number of elements in the elevation map. This is because each element is processed thrice: once for the lm array, once for the rm array, and once for the final trapped water calculation.

**Space Complexity**:
The space complexity of the algorithm is **O(n)** due to the two additional arrays (lm and rm) used to store the maximum heights to the left and right of each position. These arrays linearly scale with the number of elements in the input elevation map.
21 changes: 21 additions & 0 deletions Hard/42. Trapping Rain Water/Approach 1/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
n = len(height)
lm = [0] * n
rm = [0] * n

lm[0] = height[0]
for i in range(1, n):
lm[i] = max(lm[i - 1], height[i])

rm[n - 1] = height[n - 1]
for i in range(n - 2, -1, -1):
rm[i] = max(rm[i + 1], height[i])

water = 0
for i in range(n):
water += min(lm[i], rm[i]) - height[i]

return water

0 comments on commit c0c4ca8

Please sign in to comment.