
Sponsored
Sponsored
This approach involves creating two auxiliary arrays to store the maximum heights on the left and right of each bar. With these arrays, you can calculate how much water each bar can trap.
The water trapped above a bar is determined by the minimum of the maximum heights on its left and right, minus the bar's height itself.
Time Complexity: O(n) because we traverse the height array three times where n is the length of the array.
Space Complexity: O(n) due to the additional arrays used to store the maximum heights.
1def trap(height):
2 if not height: return 0
3 n = len(height)
4 left_max = [0] * n
5 right_max = [0] * n
6 water = 0
7
8 left_max[0] = height[0]
9 for i in range(1, n):
10 left_max[i] = max(height[i], left_max[i - 1])
11
12 right_max[n - 1] = height[n - 1]
13 for i in range(n - 2, -1, -1):
14 right_max[i] = max(height[i], right_max[i + 1])
15
16 for i in range(n):
17 water += min(left_max[i], right_max[i]) - height[i]
18
19 return water
20
21height = [0,1,0,2,1,0,1,3,2,1,2,1]
22print(f"Water trapped: {trap(height)}")
23This Python implementation uses two lists, left_max and right_max, to store left and right maximum heights. It uses these to compute the trapped water as it iterates through the height array.
The two-pointer technique optimizes space by keeping track of the left and right bars with two pointers. It uses a single loop and calculates water based on the shorter of the two heights at the current pointers.
Time Complexity: O(n), where n is the length of the input array since we process each bar only once.
Space Complexity: O(1) because we use only constant extra space.
1#
This approach leverages two pointers, starting from both ends of the array and moving towards the center. It dynamically updates the maximum height seen so far from either direction and calculates water trapped at the current position based on these max heights.