Two Pointers for Container With Most Water: Leetcode Pattern to Engineering Decision
The Two Pointers technique reduces Container With Most Water from O(n²) to O(n) by exploiting a height invariant. This post covers the rationale, trade-offs, verification, and real-world extensions.
13 Jun 2026, 13:29 UTC

The problem: container with most water
You are given an array height where each element represents the height of a vertical line on the x-axis. The goal is to pick two lines that, together with the x-axis, form a container holding the maximum amount of water. Leetcode's Container With Most Water problem constrains n ≤ 10⁵, making the quadratic approach impractical for large inputs.
The two pointers invariant
Two Pointers achieves O(n) by maintaining a left index at the start and a right index at the end. The area between them is min(height[left], height[right]) × (right − left). Because width only shrinks as pointers move inward, the only way to increase area is to find a taller line. Hence, the algorithm moves the shorter pointer one step toward the center.
Engineering trade‑offs
Two Pointers is elegant, but it relies on a problem‑specific invariant. Apply it blindly to other problems and you may get incorrect results. Leetcode test suites often omit edge cases such as equal heights, empty arrays, or overflow when heights and width multiply.
Overflow is a practical concern. Computing min(h₁, h₂) × w with 32‑bit integers can wrap when heights are large. Use int64 or long for the area calculation.
| Approach | Time | Space | When to use |
|---|---|---|---|
| Brute force | O(n²) | O(1) | Small n, educational |
| Two Pointers | O(n) | O(1) | Large n, Leetcode constraints, real‑time scanning |
Verification and real‑world extensions
Test the canonical example: height = [1,8,6,2,5,4,8,3,7]. The expected output is 49 — the container formed by the lines at indices 1 and 8.
To verify locally, run the implementation with a randomly generated array of size 10⁵ and profile runtime. You should see linear scalability versus the quadratic baseline.
def max_area(height): 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
Closing
If you're solving Container With Most Water, start with Two Pointers — it turns a quadratic scan into a single pass. For production systems, validate the invariant for your data, use 64‑bit arithmetic, and consider established libraries over hand‑crafted pointer logic.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.