19. Container With Most Water
mediumAsked at UdemyMaximize the area between two height lines using two pointers — Udemy uses this to evaluate greedy intuition for capacity-planning and bandwidth-allocation problems.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array height of length n, there are n vertical lines where the i-th line has a height of height[i]. Find two lines that together with the x-axis form a container that holds the most water. Return the maximum amount of water a container can store.
Constraints
2 <= height.length <= 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 lines and compute the area — O(n^2).
- Time
- O(n^2)
- Space
- O(1)
function maxArea(height) {
let max = 0;
for (let i = 0; i < height.length; i++)
for (let j = i+1; j < height.length; j++)
max = Math.max(max, Math.min(height[i], height[j]) * (j - i));
return max;
}Tradeoff:
2. Two-pointer greedy
Start with the widest window; move the pointer with the shorter height inward, because keeping a taller wall always has at least as much potential as keeping a shorter one.
- Time
- O(n)
- Space
- O(1)
function maxArea(height) {
let left = 0, right = height.length - 1, max = 0;
while (left < right) {
const water = Math.min(height[left], height[right]) * (right - left);
max = Math.max(max, water);
if (height[left] < height[right]) left++;
else right--;
}
return max;
}Tradeoff:
Udemy-specific tips
Udemy asks about e-learning recommendation systems, content search, and marketplace algorithms — balanced mix of arrays, hash maps, and dynamic programming problems.
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 Udemy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →