Trapping Rain Water

Problem Description

Solution Explanation

Pasted image 20260708115118.png

Pasted image 20260708120646.png

Important

The reasoning to why we don't consider what the max left or right is when shifting through the height map is that we need to only find the minimum value, so if we knowingly already have the minimum value we disregard all the other values and proceed to shift the other pointer

Implementation

def trap(height: List[int]) -> int: # TC = O(n), SC = O(n)
	lp, rp, res = 0,0,0
	for i in range(len(height)):
		lp = max(height[0:i+1]) # slice from start to current pos + 1
		rp = max(height[i:len(height)]) # slice from current pos to end
		res += min(lp, rp) - height[i] # increment based on formula
	return res
class Solution:
	def trap(self, height: List[int]) -> int:
		if not height: return 0
		
		l, r = 0, len(height) - 1
		maxL, maxR = height[l], height[r]
		res = 0
		
		while l < r:
		# Keep this in mind, the right pointer only ever shifts if it
		# is less than maxL 
			if leftMax < rightMax:
				l += 1
				maxL = max(maxL, height[l])
				res += maxL - height[l]
			else:
				r -= 1
				maxR = max(maxR, height[r])
				res += maxR - height[r]
				
		return res