← Back to DSA
#11
Container With Most Water
Container With Most Water solution for LeetCode 11, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Container With Most Water
Why it belongs on this sheet
It is a classic two-pointer problem where brute force is easy to think of, but the greedy elimination is the real interview value.
Pattern
Move the limiting side
Approach
Start with the widest container. The height is limited by the shorter wall, so moving the taller wall cannot help if the shorter wall stays the bottleneck. Move the shorter side inward.
Java solution
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int best = 0;
while (left < right) {
int width = right - left;
int area = Math.min(height[left], height[right]) * width;
best = Math.max(best, area);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}
}
Complexity
- Time:
O(n) - Space:
O(1)
Interview note
What matters here is the proof idea for why moving the shorter side is safe.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)