Skip to content

Commit 78c44fc

Browse files
committed
Improve Trapping Rain Water with full docs, validation, and tests
1 parent 99df0d2 commit 78c44fc

File tree

1 file changed

+59
-6
lines changed

1 file changed

+59
-6
lines changed
Lines changed: 59 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,73 @@
1+
"""
2+
Trapping Rain Water
3+
4+
Given an array of non-negative integers representing an elevation map where the width of each bar is 1,
5+
compute how much water it can trap after raining.
6+
7+
Problem: LeetCode #42 (Hard)
8+
Link: https://leetcode.com/problems/trapping-rain-water
9+
10+
Approach: Two Pointers
11+
Time Complexity: O(n)
12+
Space Complexity: O(1)
13+
14+
Example:
15+
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
16+
Output: 6
17+
"""
18+
19+
120
def trap(height):
2-
if not height:
3-
return 0
21+
"""
22+
Calculate the amount of water trapped after raining.
23+
24+
Args:
25+
height (List[int]): List of non-negative integers representing elevation map.
26+
27+
Returns:
28+
int: Total units of trapped rainwater.
29+
30+
Raises:
31+
TypeError: If input is not a list.
32+
ValueError: If list contains negative values.
33+
"""
34+
if not isinstance(height, list):
35+
raise TypeError("Input must be a list of integers.")
36+
if any(h < 0 for h in height):
37+
raise ValueError("Elevation map cannot contain negative values.")
38+
39+
if len(height) < 3:
40+
return 0 # At least 3 bars needed to trap water
41+
442
left, right = 0, len(height) - 1
543
max_left, max_right = 0, 0
6-
water = 0
44+
total_water = 0
45+
746
while left < right:
847
if height[left] < height[right]:
948
if height[left] >= max_left:
1049
max_left = height[left]
1150
else:
12-
water += max_left - height[left]
51+
total_water += max_left - height[left]
1352
left += 1
1453
else:
1554
if height[right] >= max_right:
1655
max_right = height[right]
1756
else:
18-
water += max_right - height[right]
57+
total_water += max_right - height[right]
1958
right -= 1
20-
return water
59+
60+
return total_water
61+
62+
63+
# Example usage and test
64+
if __name__ == "__main__":
65+
# Test case from LeetCode
66+
elevation_map = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
67+
result = trap(elevation_map)
68+
print(f"Trapped Rain Water: {result} units") # Output: 6
69+
70+
# Additional edge cases
71+
print(trap([])) # 0
72+
print(trap([1])) # 0
73+
print(trap([3, 0, 2, 0, 4])) # 7

0 commit comments

Comments
 (0)