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.
Python code
23 linesfrom 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
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
- Use a deque or stack to track candidate heights for a related largest-rectangle problem
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
- Drop Elements From Start While Condition Is True in Python easy
Keep learning
Related tutorials and quizzes for this topic.