16. Container With Most Water
mediumAsked at GojekPick two vertical lines on a number line that together hold the most water and return that area.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given an integer array height of length n. There are n vertical lines drawn at positions i with heights height[i]. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store.
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
Try every pair of indices.
- 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 convergence
Start at the widest pair and always move the shorter side inward; only the shorter side can possibly produce a larger area as width shrinks.
- Time
- O(n)
- Space
- O(1)
function maxArea(height) {
let l = 0, r = height.length - 1, best = 0;
while (l < r) {
const h = Math.min(height[l], height[r]);
best = Math.max(best, h * (r - l));
if (height[l] < height[r]) l++; else r--;
}
return best;
}Tradeoff:
Gojek-specific tips
Gojek expects candidates to verbally justify why the greedy two-pointer move never skips a better answer, since their dispatch heuristics are graded on the same shape of reasoning.
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 Gojek interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →