|
| 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 | + |
1 | 20 | 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 | + |
4 | 42 | left, right = 0, len(height) - 1 |
5 | 43 | max_left, max_right = 0, 0 |
6 | | - water = 0 |
| 44 | + total_water = 0 |
| 45 | + |
7 | 46 | while left < right: |
8 | 47 | if height[left] < height[right]: |
9 | 48 | if height[left] >= max_left: |
10 | 49 | max_left = height[left] |
11 | 50 | else: |
12 | | - water += max_left - height[left] |
| 51 | + total_water += max_left - height[left] |
13 | 52 | left += 1 |
14 | 53 | else: |
15 | 54 | if height[right] >= max_right: |
16 | 55 | max_right = height[right] |
17 | 56 | else: |
18 | | - water += max_right - height[right] |
| 57 | + total_water += max_right - height[right] |
19 | 58 | 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