Container With Most Water
Pick two lines that form the container with maximum area.
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
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.
Moving the taller side cannot help because width shrinks and the shorter wall still limits height.
Write down what each pointer means before you move them.
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
Moving both pointers without a proof.
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.