Skip to content

Instantly share code, notes, and snippets.

@ThomasHigginson
Created March 31, 2022 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasHigginson/52c148723eb5fb3a6fedbe336b234c9a to your computer and use it in GitHub Desktop.
Save ThomasHigginson/52c148723eb5fb3a6fedbe336b234c9a to your computer and use it in GitHub Desktop.
# This is the 2 pointer Solution/Approach
# It utilizes the fact that the amount of water a position
# can contain is bounded by the smallest wall to its left and right
# If the left < right, then we KNOW that it can contain whatever
# amount of water with respect to the height of the left wall (the smaller wall).
# and vice versa
def trap(self, height: List[int]) -> int:
leftMax, rightMax, ans = 0, 0, 0
left, right = 0, len(height)-1
while left < right:
if height[left] < height[right]:
if height[left] < leftMax: # Can contain water
ans += leftMax - height[left]
else:
leftMax = height[left]
left += 1
else: # height[right] >= height[left]
if height[right] < rightMax: # Can contain water
ans += rightMax - height[right]
else:
rightMax = height[right]
right -= 1
return ans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment