#42
Trapping Rain Water
HardArrayTwo PointersDynamic ProgrammingStackMonotonic StackTwo PointersDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses two pointers to traverse the height array from both ends towards the center. By maintaining the maximum heights seen from both sides, we can efficiently calculate the trapped water without redundant calculations.
⚙️
Algorithm
6 steps- 1Step 1: Initialize two pointers, left and right, at the start and end of the height array, and two variables left_max and right_max to track the maximum heights.
- 2Step 2: While left is less than right, compare left_max and right_max.
- 3Step 3: If left_max is less than right_max, calculate the trapped water at the left pointer and move the left pointer to the right.
- 4Step 4: If right_max is less than or equal to left_max, calculate the trapped water at the right pointer and move the right pointer to the left.
- 5Step 5: Continue until the two pointers meet.
- 6Step 6: Return the total trapped water.
solution.py14 lines
1def trap(height):
2 left, right = 0, len(height) - 1
3 left_max, right_max = 0, 0
4 water = 0
5 while left < right:
6 if height[left] < height[right]:
7 left_max = max(left_max, height[left])
8 water += left_max - height[left]
9 left += 1
10 else:
11 right_max = max(right_max, height[right])
12 water += right_max - height[right]
13 right -= 1
14 return waterℹ
Complexity note: The time complexity is O(n) because we traverse the height array once, and the space complexity is O(1) since we only use a few extra variables.
- 1The water trapped above a bar depends on the minimum of the maximum heights to its left and right.
- 2Using two pointers reduces the need for nested loops, improving efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.