Container With Most Water – Solution & Complexity

1. Understand the Area Formula

  • Choose two vertical lines at indices left and right.
  • The width is right - left.
  • The height of the water is limited by the shorter line.
  • Area is (right - left) * min(height[left], height[right]).

2. Brute Force Idea

  • Check every pair of lines and compute its area.
  • Keep the maximum area found.
  • This is simple but O(n²), which is too slow for large arrays.
def max_area(height):
    best = 0
    for left in range(len(height)):
        for right in range(left + 1, len(height)):
            width = right - left
            water_height = min(height[left], height[right])
            best = max(best, width * water_height)
    return best

3. Use Two Pointers

  • Start with the widest possible container: first and last lines.
  • Compute the area, then move one pointer inward.
  • Moving the taller line cannot help because the shorter line still limits the height while width shrinks.
  • Therefore, always move the pointer at the shorter line.

4. Update the Best Area While Moving

  • At each step, calculate the current area.
  • Update best if this area is larger.
  • Move left when the left line is shorter, otherwise move right.
left = 0
right = len(height) - 1
best = 0

while left < right:
    width = right - left
    water_height = min(height[left], height[right])
    best = max(best, width * water_height)

    if height[left] < height[right]:
        left += 1
    else:
        right -= 1

5. Final Solution and Complexity

  • The two pointers scan inward in one pass.
  • Every possible useful candidate is considered without checking all pairs.
  • Time complexity is O(n).
  • Space complexity is O(1).
def max_area(height: list[int]) -> int:
    left = 0
    right = len(height) - 1
    best = 0

    while left < right:
        width = right - left
        water_height = min(height[left], height[right])
        best = max(best, width * water_height)

        if height[left] < height[right]:
            left += 1
        else:
            right -= 1

    return best

FAQ

See also: