16. Container With Most Water
mediumAsked at SoFiFind two lines that form the largest water-holding container — SoFi uses this two-pointer classic to test whether candidates can reason about monotonic invariants.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given n non-negative integers representing heights of vertical lines, find two lines that together with the x-axis form a container that holds the most water. Return the maximum amount of water.
Constraints
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4
Examples
Example 1
[1,8,6,2,5,4,8,3,7]49Example 2
[1,1]1Approaches
1. Brute force pairs
Check every (i, j) pair and compute area.
- Time
- O(n^2)
- Space
- O(1)
function maxArea(height) {
let best = 0;
for (let i = 0; i < height.length; i++)
for (let j = i+1; j < height.length; j++)
best = Math.max(best, Math.min(height[i], height[j]) * (j - i));
return best;
}Tradeoff:
2. Two pointers
Start at the widest container; always move the pointer at the shorter line inward, since moving the taller one cannot increase area.
- Time
- O(n)
- Space
- O(1)
function maxArea(height) {
let left = 0, right = height.length - 1, best = 0;
while (left < right) {
const area = Math.min(height[left], height[right]) * (right - left);
best = Math.max(best, area);
if (height[left] < height[right]) left++;
else right--;
}
return best;
}Tradeoff:
SoFi-specific tips
SoFi grades on whether you can articulate the invariant — being able to explain why moving the taller pointer cannot help maps directly to portfolio-optimization arguments around dominated allocations.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Container With Most Water and other SoFi interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →