Container With Most Water
LeetCode 11 · Medium · solution, intuition & step-by-step walkthrough
Move the shorter line inward.
This is how I solved Container With Most Water (LeetCode 11), a medium problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Start with the widest container. Its height is limited by the shorter wall, and moving the taller wall inward can only shrink width without raising that limit — so always move the shorter wall and hope for a taller one.
Approach
- 1
left = 0, right = n − 1.
- 2
Area = min(height) × width; track the max.
- 3
Move whichever pointer has the smaller height.
How I solved it
Two pointersPythonO(n) time · O(1) space
class Solution:
def maxArea(self, height: List[int]) -> int:
left =0
right = len(height)-1
max_area = 0
while left<right:
min_height = min(height[left],height[right])
max_area = max(max_area,min_height*(right-left))
if height[left]<height[right]:
left+=1
else:
right-=1
return max_areaContainer With Most Water — FAQ
What is the intuition behind Container With Most Water?
Start with the widest container. Its height is limited by the shorter wall, and moving the taller wall inward can only shrink width without raising that limit — so always move the shorter wall and hope for a taller one.
How do you solve Container With Most Water (LeetCode 11)?
1. left = 0, right = n − 1. 2. Area = min(height) × width; track the max. 3. Move whichever pointer has the smaller height.
What is the time and space complexity of Container With Most Water?
Time: O(n). Space: O(1). (Accepted approach: Two pointers.)
What are common mistakes in Container With Most Water?
Moving the taller side can never help — that's the proof of correctness.