Skip to lesson

Container with most water

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.

ContainerArea.javaJava
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);    }}
Output
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.

  1. Set left = 0, right = height.length - 1, and maxArea = 0.
  2. While left < right, compute area = (right - left) * Math.min(height[left], height[right]) and update maxArea.
  3. If height[left] <= height[right], increment left++; otherwise decrement right--.

Container With Most Water on height = [1, 8, 6, 2, 5, 4, 8, 3, 7]

Step 1 of 6

Array: 1, 8, 6, 2, 5, 4, 8, 3, 7. left at index 0. right at index 8.
width
8
minH
1
area
8
best
8
Start at maximum width (0..8). Area is 8 × min(1, 7) = 8. Because height[0] = 1 is shorter than height[8] = 7, move left++.

Example 1 · Brute force: check every pair of walls (O(n²) time, O(1) space)

ContainerBrute.javaJava
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}));    }}
Output
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)

ContainerMostWaterDemo.javaJava
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}));    }}
Output
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 area 8 * min(1, 7) = 8. Since height[0] = 1 <= 7, left moves to 1 (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

ContainerTraceDemo.javaJava
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});    }}
Output
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 than right=3(h=6), so left increments to 1.
  • Step 2: left=1(h=7) and right=3(h=6) give area = 2 * 6 = 12. Now right=3(h=6) is shorter, so right decrements to 2.

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 - left is strictly smaller than right - left.
  • The new bottleneck height min(height[left], height[k]) is at most height[left] (even if height[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?

int[] h = {3, 9, 4};
int left = 0, right = 2;
int area = (right - left) * Math.min(h[left], h[right]);
if (h[left] <= h[right]) left++; else right--;
System.out.println(area + " " + left + " " + right);

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

TrappingRainWaterDemo.javaJava
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}));    }}
Output
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], leftMax cannot exceed the highest bar seen on the right (because height[right] is at least as tall as every height[left] processed so far). Thus min(leftMax, trueRightMax) == leftMax.
  • Updating leftMax = Math.max(leftMax, height[left]) before subtracting height[left] ensures leftMax - 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 as height[left] (and leftMax) exists on the right at right. Therefore the bottleneck for index left is guaranteed to be leftMax! Update leftMax = Math.max(leftMax, height[left]), add leftMax - height[left] to water, and advance left++.
  • Otherwise (height[left] > height[right]), the bottleneck for index right is guaranteed to be rightMax. Update rightMax = Math.max(rightMax, height[right]), add rightMax - height[right] to water, and retreat right--.
Container With Most Water picks two lines (ignoring bars in between); Trapping Rain Water sums water above every bar between leftMax and rightMax.

Next step

Check your understanding

10 quick questions