PracticeNeetCode ↗LeetCode ↗
Given n non-negative integers height representing an elevation map where each bar has width 1, compute how much water it can trap after it rains.
i is min(max height to its left, max height to its right) - height[i] — the smaller of the two boundary walls decides how high the water can sit.left = 0, right = len(height) - 1, left_max = 0, right_max = 0, water = 0.left < right: if height[left] < height[right], update left_max = max(left_max, height[left]), add left_max - height[left] to water, then advance left.right_max = max(right_max, height[right]), add right_max - height[right] to water, then pull right back.water.Time: O(n) — Space: O(1)
def trap(height: list[int]) -> int:
left, right = 0, len(height) - 1
left_max, right_max = 0, 0
water = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
water += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
water += right_max - height[right]
right -= 1
return waterHow the solution above works, piece by piece.
left_max and right_max: the tallest wall seen so far from each side.if height[left] < height[right]: the left side is lower, so the water over left depends only on left_max. A wall at least as tall as height[right] is guaranteed on the right.left_max, add left_max - height[left] (0 if this bar is the new max) and move left right.Running it on height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]: