Container with most water. Why does moving the shorter line work?
Problem
Given heights of vertical lines, choose two lines that, with the x-axis, hold the most water. [1, 8, 6, 2, 5, 4, 8, 3, 7] → 49.
Pattern
Converging two pointers with a greedy argument: start with the widest container and discard the side that can never be part of a better answer.
Approach 1: Try every pair (feasible, O(n²))
class ContainerBrute {
static int maxArea(int[] h) {
int best = 0;
for (int i = 0; i < h.length; i++)
for (int j = i + 1; j < h.length; j++)
best = Math.max(best, Math.min(h[i], h[j]) * (j - i));
return best;
}
}Approach 2: Two pointers moving the shorter side (O(n)) — optimal
Area is limited by the shorter line. Moving the taller line inward can only shrink the width without raising the limit, so it can never help; moving the shorter line is the only chance to find a taller limit.
class ContainerTwoPointers {
static int maxArea(int[] h) {
int left = 0, right = h.length - 1, best = 0;
while (left < right) {
best = Math.max(best, Math.min(h[left], h[right]) * (right - left));
if (h[left] < h[right]) left++; else right--;
}
return best;
}
}
class ContainerDemo {
public static void main(String[] args) {
int[] h = {1, 8, 6, 2, 5, 4, 8, 3, 7};
System.out.println(ContainerBrute.maxArea(h) + " " + ContainerTwoPointers.maxArea(h)); // 49 49
}
}Feasible → optimal
O(n²) by trying every pair → O(n) with two pointers. Be ready to explain why discarding the shorter side is safe: every container using that shorter line with any line inside the current range has smaller width and the same or lower limit.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): trapping rain water.
Also two pointers from both ends, but you add water at every step: track leftMax/rightMax and advance the side with the smaller maximum, adding max - height (see the trapping rain water question). O(n), O(1).
Related (same pattern): boats to save people (each boat carries at most two people under a weight limit).
Sort weights; pair the heaviest remaining person (hi) with the lightest (lo) if they fit together, otherwise the heaviest goes alone. Each step uses one boat; O(n log n) for the sort, O(n) for the greedy two-pointer scan.