You are given an array height where the element at index i represents the height of a bar. The width of each bar is assumed to be 1. You need to calculate the amount of water that can be trapped between the bars.
Write a function trappedWater(height: List[int]) -> int that returns the total units of water that can be trapped.
Example:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Note:
In this example, heights of the bars are represented by the numbers [0,1,0,2,1,0,1,3,2,1,2,1]. The water trapped between the bars is shown below:
|
|███|
████|███|
The problem of trapping rainwater can be efficiently solved using the Two Pointers approach. Here is the step-by-step explanation:
left and right, to point to the first and last indices of the height array, respectively.maxLeft and maxRight, to keep track of the maximum heights encountered from the left and right side, respectively. Set both to 0 initially.water to 0, which will represent the total units of water trapped.left pointer is less than or equal to the right pointer:
left index is less than or equal to the height at the right index.
left index with maxLeft.
maxLeft, update maxLeft to the current height.left index:
maxLeft minus the height at the left index to the water variable.left pointer.right pointer and maxRight instead.water which represents the total units of water trapped.Here's the Python implementation of the trappedWater function:
def trappedWater(height: List[int]) -> int:
left = 0
right = len(height) - 1
maxLeft = 0
maxRight = 0
water = 0
while left <= right:
if height[left] <= height[right]:
if height[left] > maxLeft:
maxLeft = height[left]
else:
water += maxLeft - height[left]
left += 1
else:
if height[right] > maxRight:
maxRight = height[right]
else:
water += maxRight - height[right]
right -= 1
return water
The time complexity of this solution is O(n), where n is the number of elements in the height array. This is because we iterate through the array only once.