Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

container-with-most-water.py

two-pointers/container-with-most-water.py · Python · 540 B · 2026-02-17 21:07

Back to folder
# Think of the formula to calculate water given two heights. Two pointers from left and right, move the one with the smaller height.
# two-pointers

# O(n) time, O(1) space
def max_area(height: list[int]) -> int:
    left = 0
    right = len(height) - 1
    max_water = 0
    while left < right:
        current_water = min(height[left], height[right]) * (right - left)
        max_water = max(max_water, current_water)
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return max_water