Skip to main content

14. Container With Most Water

mediumAsked at Adyen

Pick two lines forming a container with the x-axis that holds the most water.

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

Problem

Given an integer array height where each element represents a vertical line, find two lines that together with the x-axis form a container that contains the most water. Return the maximum amount of water.

Constraints

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

Examples

Example 1

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

Example 2

Input
height = [1,1]
Output
1

Approaches

1. Brute force

Try every pair of lines.

Time
O(n^2)
Space
O(1)
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-pointer shrink

Start at both ends; move the shorter wall inward each step.

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

Tradeoff:

Adyen-specific tips

Adyen sees this as a routing-window optimization — they want you to articulate why moving the taller wall can never improve the answer.

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 Adyen interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →