Skip to main content

18. Container With Most Water

mediumAsked at Mercury

Pick two lines that, together with the x-axis, contain the largest amount of water.

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

Problem

Given n vertical lines whose heights are given by an array, find two lines that together with the x-axis form a container holding the most water. Return the maximum area.

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. All pairs

Try every pair and compute width * min(left,right).

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

Tradeoff:

2. Two pointer shrink

Start with the widest pair and move whichever pointer holds the shorter line inward, since width only decreases and the shorter line is the cap.

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

Tradeoff:

Mercury-specific tips

Mercury frames this as picking the widest reconciliation window in an ACH batch — the lower-balance side gates how much you can sweep, just as the shorter wall caps water.

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

Practice these live with InterviewChamp.AI →