Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

trapping-rain-water.py

two-pointers/trapping-rain-water.py · Python · 1.2 KiB · 2026-02-17 21:07

Back to folder
# Formula to calculate the trapped water at position i: min(left_max[i], right_max[i]) - height[i]
# two-pointers

# O(n) time, O(n) space
def trap(height: list[int]) -> int:
    if not height:
        return 0

    n = len(height)
    left_max = [0] * n
    right_max = [0] * n

    left_max[0] = height[0]
    for i in range(1, n):
        left_max[i] = max(left_max[i - 1], height[i])
        
    right_max[n - 1] = height[n - 1]
    for i in range(n - 2, -1, -1):
        right_max[i] = max(right_max[i + 1], height[i])

    trapped_water = 0
    for i in range(n):
        trapped_water += min(left_max[i], right_max[i]) - height[i]
    return trapped_water


# Two pointers. O(n) time, O(1) space
def trap(height: list[int]) -> int:
    if not height:
        return 0
    left = 0
    right = len(height) - 1
    left_max = height[left]
    right_max = height[right]
    trapped_water = 0
    while left < right:
        if left_max < right_max:
            left += 1
            left_max = max(left_max, height[left])
            trapped_water += left_max - height[left]
        else:
            right -= 1
            right_max = max(right_max, height[right])
            trapped_water += right_max - height[right]
    return trapped_water