Skip to main content

15. Container With Most Water

mediumAsked at Postman

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

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

Problem

You are given an integer array height of length n. There are n vertical lines drawn at i with height height[i]. Find two lines that form a container with the x-axis holding the most water and return the maximum area.

Constraints

  • 2 <= n <= 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

Check every pair (i, j) and track the max min-height * width.

Time
O(n^2)
Space
O(1)
for i: for j>i: best = max(best, Math.min(h[i],h[j]) * (j-i))

Tradeoff:

2. Two pointers

Start with the widest pair; always move the shorter side inward since it limits the area.

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

Tradeoff:

Postman-specific tips

Postman likes greedy-two-pointer proofs out loud — interviewers want to hear why moving the shorter side is safe, the same kind of invariant reasoning they expect in proxy throttling logic.

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

Practice these live with InterviewChamp.AI →