Container With Most Water: Two-Pointer Solution in Python

Find the maximum water a container can hold from a list of heights using an efficient two-pointer technique in O(n) time.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

23 lines
Python 3.9+
from typing import List

def max_water_container(heights: List[int]) -> int:
    left, right = 0, len(heights) - 1
    max_area = 0
    
    while left < right:
        width = right - left
        height = min(heights[left], heights[right])
        area = width * height
        max_area = max(max_area, area)
        
        if heights[left] < heights[right]:
            left += 1
        else:
            right -= 1
    
    return max_area

if __name__ == "__main__":
    heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]
    result = max_water_container(heights)
    print(f"Maximum water container area for {heights}: {result}")

Output

stdout
Maximum water container area for [1, 8, 6, 2, 5, 4, 8, 3, 7]: 49

How it works

The two-pointer approach starts with the widest possible container (outermost lines) and narrows inward. At each step, the area is computed as width multiplied by the minimum of the two heights because water overflows at the shorter line. The pointer with the shorter height is moved inward because moving the taller one cannot increase the area—the height is limited by the shorter line, and the width only decreases. This guarantees the algorithm tests the optimal candidate, achieving linear time without checking every pair.

Common mistakes

  • Using an O(n²) nested-loop brute force instead of two pointers
  • Moving the taller pointer instead of the shorter one, missing the optimal area
  • Forgetting to include the line height when both heights are equal

Variations

  1. Use a deque or stack to track candidate heights for a related largest-rectangle problem
  2. Implement with a while loop that compares areas and stores the result in a list for analysis

Real-world use cases

  • Optimizing warehouse shelf layouts by maximizing the volume between vertical dividers.
  • Choosing two data centers in a network that maximize bandwidth based on capacity constraints.
  • Balancing load across servers by pairing endpoints with maximum throughput potential.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.