Two Pointers· 25 min

Container With Most Water

LeetCode #11 · Medium · Interactive step-by-step visualization

Setup

Example inputheight = [1,8,6,2,5,4,8,3,7]
Step 1 / 25

Current step

1 / 25

Measure walls 0 and 8. The area is the shorter wall times the distance between them. min(1, 7) × 8 = 8.

Step log

Container cross-section

Walls stay fixed. Only the left and right pointers move.

Current area

min(1, 7) × 8 = 8

2468water height = 1width = 8108162235445863778LR
Water held nowBest containerShorter wall moves

width

8

area

8

best

0

Active cursor
Comparing
Best or completed
Leaving or removed
container-with-most-water.java
1public int maxArea(int[] height) {
2 int left = 0, right = height.length - 1, best = 0;
3 while (left < right) {
4 int area = Math.min(height[left], height[right]) * (right - left);
5 best = Math.max(best, area);
6 if (height[left] <= height[right]) left++;
7 else right--;
8 }
9 return best;
10}
● Java
Time
O(n)
Space
O(1)
Pattern
two pointers
Frames
25