The “Container With Most Water” problem involves an array of non-negative integers, where each value represents the height of a vertical line drawn on the x-axis. The task is to find the two lines that, together with the x-axis, form a container that holds the most water. You are to return the maximum area of water that such a container can contain.
Example:
[1,8,6,2,5,4,8,3,7]
49
This problem is a classic in the use of the two-pointer technique and is frequently asked in coding interviews. It teaches how to maximize values under constraints, how to analyze trade-offs between width and height, and how to approach optimization without checking every possibility.
The naive approach would involve checking the area formed by every possible pair of lines. This means two nested loops and a time complexity of O(n²), which is inefficient for large inputs.
Since the area is determined by the shorter of two lines and the distance between them, we can use two pointers to efficiently find the maximum area. This method starts with the widest possible container (the outermost two lines) and moves inward to find better options.
left = 0
(start of array)right = height.length - 1
(end of array)max_area = 0
.left < right
:
width = right - left
.min_height = min(height[left], height[right])
.area = width × min_height
.max_area
if area
is larger.height[left] < height[right]
, increment left
.right
.max_area
.
Input: [1,8,6,2,5,4,8,3,7]
49
Time Complexity: O(n), where n is the number of lines. Each line is visited at most once by either pointer.
Space Complexity: O(1), since we only use a few variables for tracking indices and maximum area.
The “Container With Most Water” problem is a clever application of the two-pointer technique. By reducing the problem from quadratic to linear time, this solution demonstrates how leveraging input structure and greedy decision-making leads to highly efficient algorithms.