Container with most water
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Remarkably, converging two pointers can work on an unsorted array when the objective function has a bottleneck that lets you rule out one side. In both Container With Most Water and Trapping Rain Water, the water level is capped by the shorter boundary, telling us exactly which pointer to move.
The area formula
In Container With Most Water, you are given an array height of n vertical lines at positions 0, 1, …, n - 1.
public class ContainerArea { public static void main(String[] args) { int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7}; int left = 1, right = 8; int width = right - left; // 7 int water = Math.min(height[left], height[right]); // the shorter wall: 7 System.out.println("area = " + width * water); }}area = 49
Picking two lines at indices left and right (left < right) forms a rectangular container with:
- Width: right - left
- Height: min(height[left], height[right]) (because water spills over the shorter wall)
- Area: (right - left) × min(height[left], height[right])
Checking all (n(n-1))/2 pairs with nested loops takes O(n²) time, which times out when n = 10⁵.
- Width is always
right - left. - Water height is always bottlenecked by
Math.min(height[left], height[right]). - Start at maximum width (
left = 0, right = n - 1) and shrink inward.
Why we move the shorter side
When we start at left = 0 and right = n - 1, the container has the widest possible base (n - 1). Every inward step decreases the width right - left by 1.
- Set
left = 0,right = height.length - 1, andmaxArea = 0. - While
left < right, computearea = (right - left) * Math.min(height[left], height[right])and updatemaxArea. - If
height[left] <= height[right], incrementleft++; otherwise decrementright--.
Container With Most Water on height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Step 1 of 6
- width
- 8
- minH
- 1
- area
- 8
- best
- 8
Example 1 · Brute force: check every pair of walls (O(n²) time, O(1) space)
public class ContainerBrute { public static int maxArea(int[] height) { int best = 0; for (int i = 0; i < height.length; i++) { for (int j = i + 1; j < height.length; j++) { int area = (j - i) * Math.min(height[i], height[j]); best = Math.max(best, area); } } return best; }
public static void main(String[] args) { System.out.println("Max area [1,8,6,2,5,4,8,3,7]: " + maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7})); System.out.println("Max area [1,1]: " + maxArea(new int[]{1, 1})); }}Max area [1,8,6,2,5,4,8,3,7]: 49 Max area [1,1]: 1
What this code does
- Every pair of walls is measured: width times the shorter height. About n × n / 2 areas are computed, so n = 100,000 is too slow.
- Most of those pairs can never win. A pair with a shorter wall and a smaller width than one already seen is wasted work, and two pointers can skip all of them.
Example 2 · Optimal: two pointers, always move the shorter wall (O(n) time, O(1) space)
public class ContainerMostWaterDemo { public static int maxArea(int[] height) { int left = 0; int right = height.length - 1; int best = 0;
while (left < right) { int h = Math.min(height[left], height[right]); int area = (right - left) * h; if (area > best) { best = area; } if (height[left] <= height[right]) { left++; } else { right--; } } return best; }
public static void main(String[] args) { System.out.println("Max area [1,8,6,2,5,4,8,3,7]: " + maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7})); System.out.println("Max area [1,1]: " + maxArea(new int[]{1, 1})); }}Max area [1,8,6,2,5,4,8,3,7]: 49 Max area [1,1]: 1
What this code does
- On
[1, 8, 6, 2, 5, 4, 8, 3, 7], start at(0, 8)with area8 * min(1, 7) = 8. Sinceheight[0] = 1 <= 7,leftmoves to1(height[1] = 8), where(8 - 1) * min(8, 7) = 7 * 7 = 49. - Every step discards the shorter wall, finishing in n - 1 iterations.
- Why it is faster: moving the taller wall can only shrink the width without raising the limiting height, so it is safe to drop the shorter wall. Each step removes a whole group of pairs.
Example 3 · Tracing Container With Most Water step by step
public class ContainerTraceDemo { public static void traceMaxArea(int[] height) { int left = 0, right = height.length - 1, best = 0; while (left < right) { int area = (right - left) * Math.min(height[left], height[right]); best = Math.max(best, area); System.out.printf("left=%d(h=%d), right=%d(h=%d) -> area=%d, best=%d%n", left, height[left], right, height[right], area, best); if (height[left] <= height[right]) left++; else right--; } }
public static void main(String[] args) { traceMaxArea(new int[]{2, 7, 5, 6}); }}left=0(h=2), right=3(h=6) -> area=6, best=6 left=1(h=7), right=3(h=6) -> area=12, best=12 left=1(h=7), right=2(h=5) -> area=5, best=12
What this code does
- Step 1:
left=0(h=2)is shorter thanright=3(h=6), soleftincrements to1. - Step 2:
left=1(h=7)andright=3(h=6)givearea = 2 * 6 = 12. Nowright=3(h=6)is shorter, sorightdecrements to2.
Therefore, the only way an inner pair can beat our current area is by finding a strictly taller bottleneck height.
Suppose height[left] <= height[right]. What happens if we keep left fixed and move right inward to any index k (left < k < right)?
- The new width
k - leftis strictly smaller thanright - left. - The new bottleneck height
min(height[left], height[k])is at mostheight[left](even ifheight[k]is a million units tall,height[left]still caps the water!).
Thus, no partner k between left + 1 and right - 1 can ever form a larger container with left than right already did! We can safely discard left (left++) without losing the optimal pair. Symmetrically, when height[left] > height[right], we discard right (right--).
Predict the output
Which pointer moves?
Work out the printed values.
What does this code print?
Trapping rain water with two pointers
In Trapping Rain Water, each index i is a solid bar of width 1 and height height[i], and we want the total water trapped above all bars.
Example 4 · Trapping Rain Water in O(n) time and O(1) space
public class TrappingRainWaterDemo { public static int trap(int[] height) { int left = 0, right = height.length - 1; int leftMax = 0, rightMax = 0; int totalWater = 0;
while (left < right) { if (height[left] <= height[right]) { leftMax = Math.max(leftMax, height[left]); totalWater += leftMax - height[left]; left++; } else { rightMax = Math.max(rightMax, height[right]); totalWater += rightMax - height[right]; right--; } } return totalWater; }
public static void main(String[] args) { System.out.println("Trapped [0,1,0,2,1,0,1,3,2,1,2,1]: " + trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1})); System.out.println("Trapped [4,2,0,3,2,5]: " + trap(new int[]{4, 2, 0, 3, 2, 5})); }}Trapped [0,1,0,2,1,0,1,3,2,1,2,1]: 6 Trapped [4,2,0,3,2,5]: 9
What this code does
- When
height[left] <= height[right],leftMaxcannot exceed the highest bar seen on the right (becauseheight[right]is at least as tall as everyheight[left]processed so far). Thusmin(leftMax, trueRightMax) == leftMax. - Updating
leftMax = Math.max(leftMax, height[left])before subtractingheight[left]ensuresleftMax - height[left]is never negative.
The water level above bar i is determined by the tallest bar to its left (leftMax) and the tallest bar to its right (rightMax):
water[i] = max(0, min(leftMax[i], rightMax[i]) - height[i])
Precomputing leftMax[] and rightMax[] arrays takes O(n) time and O(n) space. Two pointers reduces space to O(1)!
Maintain left = 0, right = n - 1, leftMax = 0, and rightMax = 0:
- If
height[left] <= height[right], we know a bar at least as tall asheight[left](andleftMax) exists on the right atright. Therefore the bottleneck for indexleftis guaranteed to beleftMax! UpdateleftMax = Math.max(leftMax, height[left]), addleftMax - height[left]towater, and advanceleft++. - Otherwise (
height[left] > height[right]), the bottleneck for indexrightis guaranteed to berightMax. UpdaterightMax = Math.max(rightMax, height[right]), addrightMax - height[right]towater, and retreatright--.
leftMax and rightMax.Next step
Check your understanding
10 quick questions