- Initialize two pointers,
left
andright
, at the beginning and end of the elevation map, respectively. - Initialize two variables,
leftMax
andrightMax
, to 0. These will keep track of the maximum heights on the left and right sides. - Initialize a variable
trappedWater
to 0 to keep track of the accumulated trapped water. - While
left
is less thanright
, do the following: a. Ifheight[left]
is less thanheight[right]
, calculate the trapped water on the left side:- If
height[left]
is greater than or equal toleftMax
, updateleftMax
toheight[left
. - Otherwise, add
leftMax - height[left]
totrappedWater
. - Increment
left
. b. Ifheight[right]
is less than or equal toheight[left]
, calculate the trapped water on the right side: - If
height[right]
is greater than or equal torightMax
, updaterightMax
toheight[right]
. - Otherwise, add
rightMax - height[right]
totrappedWater
. - Decrement
right
.
- If
- Continue this process until
left
is less thanright
. - Return the
trappedWater
as the final result.
The time complexity of the given algorithm is``O(n)`, where n is the number of elements (bars) in the elevation map. This is because the algorithm processes each element once using two pointers, and the while loop iterates through the elements at most once from left to right and right to left. Since each element is processed once, the time complexity is linear with respect to the number of elements.
The space complexity of the algorithm is O(1)
, which means it uses a constant amount of extra space. Regardless of the size of the input elevation map, the algorithm only uses a fixed number of variables to keep track of left and right pointers, leftMax, rightMax, and trappedWater. The memory usage does not depend on the size of the input, so the space complexity is constant.