16. Container With Most Water
mediumAsked at GrabPick two lines forming the largest water container — Grab uses this as a two-pointer optimization test.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given n non-negative integers a_1, a_2, ..., a_n where each represents a point at coordinate (i, a_i), find two lines that form the container with the most water.
Constraints
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4
Examples
Example 1
height = [1,8,6,2,5,4,8,3,7]49Example 2
height = [1,1]1Approaches
1. Brute force pairs
Try every (i, j) pair and compute the area.
- Time
- O(n^2)
- Space
- O(1)
let best = 0;
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
best = Math.max(best, (j - i) * Math.min(height[i], height[j]));Tradeoff:
2. Two-pointer shrink
Start from both ends; always move the shorter wall inward since shrinking width can only help if height grows.
- Time
- O(n)
- Space
- O(1)
function maxArea(height) {
let l = 0, r = height.length - 1, best = 0;
while (l < r) {
const area = (r - l) * Math.min(height[l], height[r]);
if (area > best) best = area;
if (height[l] < height[r]) l++;
else r--;
}
return best;
}Tradeoff:
Grab-specific tips
Grab interviewers grade whether you justify shrinking the shorter wall — frame as picking the best two pickup zones to maximize ride supply coverage.
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 Grab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →