Intuition
The problem involves calculating the amount of water that can be trapped between the bars of an elevation map after raining. The idea is to use a two-pointer approach to determine the maximum height of bars on the left and right of each position and calculate the water trapped at each position.
Approach
The provided solution uses a two-pointer approach to iterate through the elevation map and calculate the trapped water at each position.
Initialize two pointers, left and right, at the beginning and end of the elevation map, respectively.
Initialize variables leftmax and rightmax to keep track of the maximum height of bars on the left and right, respectively. Set them to the height of the first and last bars.
Initialize a variable res to keep track of the total trapped water.
While the left pointer is less than the right pointer:
If leftmax is less than rightmax, move the left pointer to the right and update leftmax. Calculate and add the trapped water at the current position to res.
If rightmax is less than or equal to leftmax, move the right pointer to the left and update rightmax. Calculate and add the trapped water at the current position to res.
Repeat the process until the pointers meet.
Complexity
- Time complexity:
The time complexity of this solution is O(n), where n is the length of the input array height. The two-pointer approach allows for a single pass through the elevation map.
- Space complexity:
The space complexity is O(1), as the solution uses only a constant amount of space to store pointers and variables.
Code
class Solution:
def trap(self, height: List[int]) -> int:
if not height: return 0
left , right = 0 , len(height) - 1
leftmax,rightmax = height[left] , height[right]
res=0
while left < right :
if leftmax < rightmax:
left+=1
leftmax=max(height[left],leftmax)
res += leftmax - height[left]
else:
right-=1
rightmax=max(height[right],rightmax)
res += rightmax -height[right]
return res