Always settle the column under the shorter wall — its water level is already fully determined.
Whichever side is currently shorter has a taller bar waiting on the other side, so its water level equals its own running maximum. Add that column's water, advance that pointer, repeat.
Algorithm
l = 0,r = n − 1,leftMax = rightMax = 0,water = 0.- While
l < r: ifheight[l] < height[r]:leftMax = max(leftMax, height[l]),water += leftMax − height[l],l += 1. - Else:
rightMax = max(rightMax, height[r]),water += rightMax − height[r],r −= 1. - Return
water.
- Time
- O(n)
- Space
- O(1)
class Solution: def trap(self, height: list[int]) -> int: l, r = 0, len(height) - 1 left_max = right_max = 0 water = 0 while l < r: if height[l] < height[r]: # a taller wall exists on the right, so left_max decides the level here left_max = max(left_max, height[l]) water += left_max - height[l] l += 1 else: right_max = max(right_max, height[r]) water += right_max - height[r] r -= 1 return water