Topic · Two PointersMedium
Container With Most Water
Understand the problem
Given an array height of n positive integers. Each element height[i] is the height of a vertical line at position i. Find two lines that, together with the x-axis, form a container holding the most water.
Example:
ts
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
output = 49
// Lines i=1 (height 8) and j=8 (height 7): area = min(8,7) × (8-1) = 7 × 7 = 49
height = [1, 1]
output = 1 // min(1,1) × (1-0) = 1The amount of water held = min(height[left], height[right]) × (right - left).
The container can't be tilted — only the flat (horizontal) fill counts.
Basic approach
O(n²) time, O(1) spacets
function maxArea(height: number[]): number {
let max = 0
for (let i = 0; i < height.length; i++) {
for (let j = i + 1; j < height.length; j++) {
const water = Math.min(height[i], height[j]) * (j - i)
max = Math.max(max, water)
}
}
return max
}Why this approach is slow:
- Checks every pair (i, j).
- With n=10⁵ → 5·10⁹ pairs — far too slow.
- The optimization trick: as the two pointers move inward, the width only shrinks → to get a larger area you must increase the height, but the height is capped by the shorter line.
- So you only need to move the shorter line inward and skip a huge number of useless pairs → O(n).
Unlock the optimal solution, the step-by-step trace and related questions
See the full step-by-step trace, Big-O and edge cases.