We want to find two lines that hold the most water between them by checking pairs from the edges inward.
Analogy: Imagine two people standing on opposite ends of a riverbank holding a rope. The water they can hold between them depends on the shorter person and the distance between them. Moving the shorter person inward might find a better spot to hold more water.
move pointer at shorter line inward to try for bigger area
OutputSuccess
49
Complexity Analysis
Time: O(n) because we move two pointers inward only once each over the array
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: Compared to checking all pairs O(n^2), this two-pointer approach is much faster and efficient
Edge Cases
Empty array
Returns 0 as no container can be formed
DSA C
while (left < right) {
Array with one element
Returns 0 as container needs two lines
DSA C
while (left < right) {
All heights equal
Returns max area as height * (last index - first index)
DSA C
if (current_area > max_area) { max_area = current_area; }
When to Use This Pattern
When you need to find max area or max product between pairs in a linear structure, try two pointers from edges moving inward to optimize search.
Common Mistakes
Mistake: Moving the pointer at the taller line instead of the shorter line Fix: Always move the pointer at the shorter line inward to potentially find a taller line and larger area
Mistake: Calculating area using max height instead of min height Fix: Use the shorter line height to calculate area because water is limited by the shorter side
Summary
Finds the maximum water container by checking pairs of lines from edges inward.
Use when you want to maximize area between two lines in an array efficiently.
The key is to move the pointer at the shorter line inward to find a potentially taller line and larger area.