
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.
1public class TrappingRainWater {
2 public static int trap(int[] height) {
3 if (height == null || height.length == 0) return 0;
4 int n = height.length;
5 int[] leftMax = new int[n];
6 int[] rightMax = new int[n];
7 int water = 0;
8
9 leftMax[0] = height[0];
10 for (int i = 1; i < n; i++) {
11 leftMax[i] = Math.max(height[i], leftMax[i - 1]);
12 }
13
14 rightMax[n - 1] = height[n - 1];
15 for (int i = n - 2; i >= 0; i--) {
16 rightMax[i] = Math.max(height[i], rightMax[i + 1]);
17 }
18
19 for (int i = 0; i < n; i++) {
20 water += Math.min(leftMax[i], rightMax[i]) - height[i];
21 }
22
23 return water;
24 }
25
26 public static void main(String[] args) {
27 int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
28 System.out.println("Water trapped: " + trap(height));
29 }
30}
31The Java solution follows a similar structure to other languages, using arrays to track left and right maximum heights. The function iterates to calculate the water trapped using these arrays.
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.
1function
By leveraging two pointer methodology, this JavaScript solution efficiently handles rainwater trapping, iterating inward with simultaneous comparisons and dynamic allocations of max seen heights thus far.