← DSA
MEDIUM

Container With Most Water

PracticeNeetCode ↗LeetCode ↗

Given an integer array height where height[i] is the height of a vertical line at position i, find two lines that, together with the x-axis, form the container holding the most water. Return that maximum area.

Example

Input height = [1,8,6,2,5,4,8,3,7]
Output 49

Key Pointers

Step-by-Step Analysis

  1. Set left = 0, right = len(height) - 1, and best = 0.
  2. While left < right: compute area = min(height[left], height[right]) * (right - left), and update best if it's larger.
  3. Move whichever pointer points at the shorter line inward — if height[left] < height[right], advance left; otherwise pull right back.
  4. Repeat until the pointers meet; return best.

Complexity

Time: O(n) — Space: O(1)

Code

def maxArea(height: list[int]) -> int:
    left, right = 0, len(height) - 1
    best = 0

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

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

    return best

Code Explanation

How the solution above works, piece by piece.

  1. Start with the widest container: left = 0, right = n − 1.
  2. area = min(height[left], height[right]) * (right - left): water is limited by the shorter wall.
  3. Keep the best area seen.
  4. Move the pointer at the shorter wall. Any container that keeps that wall and is narrower can't be better, so it's safe to discard.
  5. One pass, each step drops one wall: O(n) time, O(1) space, instead of trying all O(n²) pairs.

Visual Walkthrough

Running it on height = [1, 8, 6, 2, 5, 4, 8, 3, 7]:

Heights with the best container between index 1 and 81862548377 × 7 = 49l r area move0 8 8 left++1 8 49 right--1 7 18 right--1 6 40 right--1 5 16 right--1 4 15 right--1 3 4 right--1 2 6 right--
Area = shorter wall × distance. Each step moves the shorter wall inward, because moving the taller one can only shrink the width without raising the limiting height. The best pair is index 1 and 8: min(8, 7) × 7 = 49.
best walls

Video Explanation

NeetCode — Container With Most Water, LeetCode 11