Container With Most Water solution explained
Container With Most Water is solved with two pointers that start at the first and last line and move inward, always advancing the shorter of the two, while tracking the largest area seen. Moving the taller line can never help, because the width shrinks and the water level stays capped by the shorter one, so a single O(n) pass with O(1) space finds the answer.
By Evin JohnPublished 7 min read
Setting up the problem
Imagine a row of vertical posts standing one unit apart, each with a height given by a list of non-negative integers. Choose any two posts and imagine a sheet of glass between them reaching down to the ground. The water it can hold is limited by the shorter post, and its width is the distance between the two posts. Return the largest amount of water any pair can hold. The posts in between do not block anything; only the two chosen ones matter.
| Heights | Most water | Chosen posts |
|---|---|---|
| [2, 7, 3, 8, 4] | 14 | Heights 7 and 8, two apart: 7 × 2 |
| [4, 1, 1, 4] | 12 | The two outer posts: 4 × 3 |
| [1, 8, 2, 1, 2, 9, 1] | 32 | Heights 8 and 9, four apart: 8 × 4 |
| [5, 5] | 5 | The only pair: 5 × 1 |
A couple of points to confirm: is the list guaranteed to have at least two posts, can heights be zero, and do you return the amount or the pair of positions? Also make sure the interviewer means this problem and not the one where water collects over every bar, which is a different question with a different answer.
What makes it a good interview question
The code is short, but the reason it is correct is not obvious, and that is the point. Many candidates guess the two-pointer loop from memory. Fewer can explain why discarding the shorter post never throws away the best answer. Interviewers often ask for that argument directly, so prepare it as carefully as the code. It also tests whether you can reason about a quantity that depends on two things at once, here width and height, and see which one you can afford to give up.
Questions that usually follow
- Why move the shorter post? Any pair that keeps the shorter post and swaps the other for one further in has a smaller width and a height still capped by that shorter post, so none of those pairs can win. The shorter post can be retired safely.
- What happens on equal heights? Moving either one is fine. Every remaining pair that keeps one of those two posts is narrower and no taller than the current pair, so the current area already beats them.
- Return the positions too. Save the two indexes whenever the best area improves.
- Posts at uneven positions. If each post has its own x coordinate in increasing order, use the difference of coordinates as the width. The argument still holds because width still shrinks as the pointers close in.
- How is this different from trapping rain water? That problem adds up water above every bar using the tallest bar on each side; here you pick only two posts and ignore the rest.
Brute force: score every pair
Loop over every left post and every right post after it, compute the shorter height times the distance, and keep the maximum. It is O(n²) time and O(1) extra space. Write it first if you are unsure, and keep it around as the checker for the faster version.
def most_water_slow(heights):
best = 0
for i in range(len(heights)):
for j in range(i + 1, len(heights)):
best = max(best, min(heights[i], heights[j]) * (j - i))
return bestOptimal approach: close in from both ends
Put one pointer on the first post and one on the last. That pair has the widest possible base. Record its area. Now one of the pointers must move inward, and the elimination argument says which: the shorter one. Every pair still to consider that keeps the shorter post is narrower and capped at the same height, so it cannot beat what you just recorded. Move the shorter pointer, record again, and repeat until the pointers meet. Each step retires one post, so there are at most n - 1 steps.
def most_water(heights):
left, right = 0, len(heights) - 1
best = 0
while left < right:
h = min(heights[left], heights[right])
best = max(best, h * (right - left))
if heights[left] < heights[right]:
left += 1
else:
right -= 1
return bestfunction mostWater(heights) {
let left = 0;
let right = heights.length - 1;
let best = 0;
while (left < right) {
const h = Math.min(heights[left], heights[right]);
best = Math.max(best, h * (right - left));
if (heights[left] < heights[right]) left++;
else right--;
}
return best;
}def most_water_pair(heights):
left, right = 0, len(heights) - 1
best, pair = 0, None
while left < right:
area = min(heights[left], heights[right]) * (right - left)
if pair is None or area > best:
best, pair = area, (left, right)
if heights[left] < heights[right]:
left += 1
else:
right -= 1
return best, pairA small speed-up some people mention: after moving a pointer, keep moving it while the new post is no taller than the one just retired, since such a post cannot form a bigger container with anything still in range. It does not change the O(n) bound, so only bring it up if there is time.
Complexity summary
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Every pair | O(n²) | O(1) | Correct and slow |
| Two pointers from both ends | O(n) | O(1) | The expected answer |
| Two pointers with positions returned | O(n) | O(1) | Same loop, two more variables |
| Sort posts by height, sweep | O(n log n) | O(n) | A valid alternative that rarely comes up and is harder to explain |
Edge cases
- Exactly two posts: one pair, one answer.
- All posts the same height: the outer pair wins, since it is the widest.
- A zero-height post at one end: that pair holds nothing, and the zero pointer moves first.
- Heights that rise steadily: the best pair is often not the two tallest posts, because they sit next to each other.
- Ties between different pairs, as in [3, 9, 9, 3], where the outer pair and the middle pair both hold 9.
- Very large heights and widths in a fixed-width integer type, where the product may need 64 bits.
Pitfalls
- Moving the taller pointer, or moving both at once, which can skip the best pair.
- Using the taller height instead of the shorter one to compute the area.
- Counting the distance as right - left + 1. The posts are the walls, so the width is the plain difference of positions.
- Confusing it with trapping rain water and summing water over every bar.
- Giving the loop without the elimination argument when the interviewer asks why it is correct.
How to explain it out loud
Fictional example
- Candidate
- Every pair would be quadratic. I start with the widest pair, the two ends, and record its area.
- Candidate
- Then I retire the shorter post. Any other partner for it is closer, so the width drops, and the height cannot rise above that shorter post. None of those pairs can beat what I already have.
- Candidate
- Each step drops one post, so it is linear. On 2, 7, 3, 8, 4 the 2 goes first, then the 4, then I see 7 and 8 two apart for 14, and nothing later beats it.
Similar two-pointer problems
3Sum runs a pointer pair inward over sorted values, moving whichever side brings the sum closer to zero. The sorted variant of Two Sum is the simplest version of the same move. For a running value carried in one direction instead, see Best Time to Buy and Sell Stock. All problems are listed on the coding problems hub.
Natively for your practice sessions
Correctness arguments are the part people skip when practicing alone. With Natively on Mac or Windows, you can take a screenshot of a problem like this during practice and get a suggested approach and code to check your own against, including why the shorter side moves. It transcribes your mock interview too, so you can reread whether your proof was clear or just a restatement of the loop. Learn more about the AI interview assistant.
Questions people ask
How do you solve Container With Most Water?
Start with pointers at the first and last post, record the area, then move the pointer at the shorter post inward. Repeat until they meet and return the largest area seen. It runs in O(n) time and O(1) space.
Why do you move the pointer with the smaller height?
Any other pair using the shorter post is narrower and still capped at that post's height, so none can hold more water than the pair you just measured. Retiring it loses nothing.
What if both heights are equal?
Move either pointer. Every remaining pair that keeps one of the two equal posts is narrower and no taller, so the current area already beats them.
Is Container With Most Water the same as Trapping Rain Water?
No. Here you choose two posts and ignore everything between them. Trapping Rain Water totals the water held above every bar, which needs the tallest bar on each side of each position.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
