The intuition behind the problem is to find out how much water can be trapped between the bars of the elevation map after raining. The amount of water trapped above a bar is determined by the height of the tallest bars to its left and right. If we know these values, we can calculate the trapped water above each bar by subtracting the bar’s height from the minimum of the tallest bars to its left and right.
- Precompute Maximum Heights:
- Use two arrays,
maxLeft
andmaxRight
, to store the maximum heights up to each index from the left and the right, respectively. - Iterate through the
height
array to fill these arrays.maxLeft[i]
stores the maximum height of the bars from the left up to indexi
.maxRight[j]
stores the maximum height of the bars from the right up to indexj
.
- Use two arrays,
- Calculate Trapped Water:
- For each bar at index
i
, the water trapped above it is determined by the minimum ofmaxLeft[i]
andmaxRight[i]
, minus the height of the bar itself (height[i]
). - Sum these values to get the total amount of trapped water.
- For each bar at index
- Implementation:
- Initialize
maxLeft
andmaxRight
arrays. - Iterate through the
height
array from both ends simultaneously to fillmaxLeft
andmaxRight
. - Iterate through the
height
array to calculate the total trapped water using the precomputed values inmaxLeft
andmaxRight
.
- Initialize
- Time Complexity: O(N)
- The first loop to fill
maxLeft
andmaxRight
runs inO(N)
time. - The second loop to calculate the trapped water also runs in
O(N)
time. - Therefore, the overall time complexity is
O(N)
.
- The first loop to fill
- Space Complexity: O(N)
- We use two additional arrays
maxLeft
andmaxRight
, each of sizeN
. - Hence, the space complexity is
O(N)
.
- We use two additional arrays