Professional Documents
Culture Documents
Presentation Trapping Water
Presentation Trapping Water
Presentation Trapping Water
Sabiha Barlaskar
PROBLEM STATEMENT
Given n non-negative integers representing an elevation map
where the width of each bar is 1, compute how much water it is
able to trap after raining.
EXAMPLE
EXAMPLE
0
0 1 0 2 1 0 1 3 2 1 2 1
LeftMax 0 1 1 2 2 2 2 3 3 3 3 3
RightMax 3 3 3 3 3 3 3 3 2 2 2 1
Min(L,R) 0 1 1 2 2 2 2 3 2 2 2 1
Min(L,R) -
Block[i]
0 0 1 0 1 2 1 0 0 1 0 0
CODE
height = [0,1,0,2,1,0,1,3,2,1,2,1]
def trap(height):
n = len(height)
leftHeight= [0] * n
rightHeight = [0] * n
water = 0
leftHeight[0] = height[0]
for i in range(1,n):
leftHeight[i] = max(height[i],leftHeight[i-1])
rightHeight[n-1] = height[n-1]
rightHeight[i] = max(height[i],rightHeight[i+1])
for i in range(1,n-1):
return water
print trap(height)
LIMITATIONS OF DYNAMIC PROGRAMMING
Time complexity is O(n)
Space complexity is O(n)
USE 2 POINTERS
Algorithm
Initialize left pointer to 0 and right pointer to size-1
While left<right, do:
If height[left] is smaller than height[right]
If height[left]>=left_max, update left_maxleft_max
Else add left_maxheight[left] to ans
Add 1 to left.
Else
If height[right]>=right_max, update right_maxright_max
Else add right_maxheight[right] to ans
Subtract 1 from right.
PROGRAM CODE IN PYTHON
height = [0,1,0,2,1,0,1,3,2,1,2,1]
def trap(height):
left = 0
right = len(height) - 1
water = 0
left_max = 0
right_max = 0
while(left<right):
if height[left]<height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
water += left_max - height[left]
left += 1
else:
if height[right]>=right_max:
right_max = height[right]
else:
water += right_max - height[right]
right -= 1
return water
print trap(height)
COMPLEXITY
Time complexity: O(n)
Space Complexity: O(1)
QUESTIONS??