#11
Medium
Two Pointers

Container With Most Water

Pick two lines that form the container with maximum area.

ArrayTwo Pointers

Pattern fit

Area is limited by the shorter line, so only moving the shorter side can possibly improve the bottleneck; that proof is why this is a signature two-pointer problem.

Key observation

Moving the taller side cannot help because width shrinks and the shorter wall still limits height.

Target complexity

O(n) / O(1)

How to break down the solution cleanly

1

Area is limited by the shorter line, so only moving the shorter side can possibly improve the bottleneck; that proof is why this is a signature two-pointer problem.

2

Moving the taller side cannot help because width shrinks and the shorter wall still limits height.

3

Write down what each pointer means before you move them.

4

Use the current comparison to prove which side can be safely discarded.

Reference implementation

Python
# Generic pattern template
# Opposite-direction pointers on a sorted array
left, right = 0, len(nums) - 1
while left < right:
    if good(nums[left], nums[right]):
        return answer
    if should_move_left(nums[left], nums[right]):
        left += 1
    else:
        right -= 1

# Fast/slow pointers
slow = 0
for fast in range(len(nums)):
    if keep(nums[fast]):
        nums[slow] = nums[fast]
        slow += 1

Common pitfalls

warning

Moving both pointers without a proof.

warning

Treating area as if taller height alone guarantees improvement.

Common follow-ups

How would you explain the correctness proof in one minute?

What changes if the x-axis distances are not uniform?

Continue with related problems

Build repeatable depth inside the Two Pointers cluster before moving on.

view_weekBack to the pattern page
LeetCode 11. Container With Most Water Guide | Interview AiBox