Skip to main content

16. Container With Most Water

mediumAsked at SoFi

Find two lines that form the largest water-holding container — SoFi uses this two-pointer classic to test whether candidates can reason about monotonic invariants.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given n non-negative integers representing heights of vertical lines, find two lines that together with the x-axis form a container that holds the most water. Return the maximum amount of water.

Constraints

  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4

Examples

Example 1

Input
[1,8,6,2,5,4,8,3,7]
Output
49

Example 2

Input
[1,1]
Output
1

Approaches

1. Brute force pairs

Check every (i, j) pair and compute area.

Time
O(n^2)
Space
O(1)
function maxArea(height) {
  let best = 0;
  for (let i = 0; i < height.length; i++)
    for (let j = i+1; j < height.length; j++)
      best = Math.max(best, Math.min(height[i], height[j]) * (j - i));
  return best;
}

Tradeoff:

2. Two pointers

Start at the widest container; always move the pointer at the shorter line inward, since moving the taller one cannot increase area.

Time
O(n)
Space
O(1)
function maxArea(height) {
  let left = 0, right = height.length - 1, best = 0;
  while (left < right) {
    const area = Math.min(height[left], height[right]) * (right - left);
    best = Math.max(best, area);
    if (height[left] < height[right]) left++;
    else right--;
  }
  return best;
}

Tradeoff:

SoFi-specific tips

SoFi grades on whether you can articulate the invariant — being able to explain why moving the taller pointer cannot help maps directly to portfolio-optimization arguments around dominated allocations.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Container With Most Water and other SoFi interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →