Faaez Razeen

Trapping Rain Water

  • 4 min read
  • LC-Hard
  • Two Pointers

3 years ago

Solution - O(n) memory

Solution - O(1) memory

TimeSpaceExplanation
O()O()
def trap(self, height: List[int]) -> int: l, r = 0, len(height) - 1 left_max, right_max = height[l], height[r] ans = 0 while l < r: if left_max < right_max: l += 1 ans += max(0, left_max - height[l]) left_max = max(left_max, height[l]) else: r -= 1 ans += max(0, right_max - height[r]) right_max = max(right_max, height[r]) return ans

Another Solution that's the same but code intuitively makes more sense because I did it on the first try while being 1 month off LeetCode, 5 hours of sleep, and no coffee

def trap(self, height: List[int]) -> int: l, r = 0, len(height) - 1 max_l, max_r = height[l], height[r] amount_trapped = 0 while l <= r: if max_l < max_r: amount_trapped += max(0, max_l - height[l]) max_l = max(max_l, height[l]) l += 1 else: amount_trapped += max(0, max_r - height[r]) max_r = max(max_r, height[r]) r -= 1 return amount_trapped

The above solution also works when you're l and r pointers start out and 1 and len(height) - 2 because you can't store water at the extremities