Skip to main content

14. Container With Most Water

mediumAsked at Klarna

Find two vertical lines that, together with the x-axis, form a container holding the most water.

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

Problem

Given an integer array height of length n where height[i] represents a vertical line at position i, find two lines that form a container holding the maximum amount of water. Return that 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. Brute force all pairs

Check every (i, j) pair and track the max area.

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

Tradeoff:

2. Two pointers

Start pointers at both ends; move the shorter side inward each step. Moving the taller side can never beat the current area, so this single pass finds the optimum.

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

Tradeoff:

Klarna-specific tips

Klarna BNPL underwriters use this 'shrink toward the limiting side' pattern when optimizing credit-score thresholds, so they grade you on whether you can explain WHY moving the taller pointer 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 Klarna interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →