Skip to the solution
MediumDSA4 min read

How do you solve the container with most water problem?

453 views

The problem

Question presented to candidate: "You get an array where each value is the height of a vertical line. Pick two lines that, together with the x-axis, hold the most water, and return that amount. Please code it in Python, and convince me your approach cannot miss the best pair."

What a strong answer should cover:

  • The area of a pair is min(height[i], height[j]) ร— (j โˆ’ i); the brute force checks all pairs in O(nยฒ).
  • Two pointers from both ends, always moving the shorter wall: O(n) time, O(1) space.
  • The elimination argument: every container that keeps the shorter wall is narrower and capped by that same wall, so discarding it is safe; moving the taller wall can never help.
  • Equal walls (move either) and edge cases: fewer than two lines, zeros, best pair adjacent.
  • Python specifics: min()/max() built-ins and tuple assignment keep it short; Python integers never overflow, so height ร— width is always exact.

Clarifying questions expected:

  • "Do you want the area only or the two indices too?"
  • "How large can heights and n get?" โ€” decides whether the area needs a 64-bit type.

Code / implementation expected: Yes โ€” a max_area(height) function in Python, ideally returning the pair of indices as well.

  • arrays
  • two-pointers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTwo pointers on seven inputs, with the winning pair
PythonTrace, then two pointers vs brute force on random arrays

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 92 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Number of islands with DFS vs BFS vs Union-Find โ€” trade-offs?

Continue