15% off all plans & roadmaps Use code

See plans

Container With Most Water

Updated

TL;DR: Pick two vertical lines so that the shorter height times the distance between them is as large as possible. Start with the widest pair and always move the pointer on the shorter line inward. This finds the answer in one O(n) pass.

Problem

You are given an integer array height of length n. The array describes n vertical lines: line i runs from (i, 0) up to (i, height[i]).

Choose two lines that, together with the x-axis, form a container holding as much water as possible. Return the maximum amount of water such a container can store. The container cannot be tilted.

Example 1

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The lines are drawn from the array [1,8,6,2,5,4,8,3,7]. The best container uses the lines of height 8 and 7, and holds 49 units of water.

Example 2

Input: height = [1,1]
Output: 1

Constraints

  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4

Constraints that matter

  • n up to 10^5 means an O(n^2) pair check does about 5 * 10^9 pair evaluations, which is too slow. You need roughly O(n) or O(n log n).
  • height[i] up to 10^4 and width up to 10^5 give a largest area of 10^9, which fits in a 32-bit signed int. No long type is needed.
  • n is at least 2, so there is always one valid pair and the loop never starts with an empty window.
  • height[i] can be 0, so an area of 0 is a legal answer when every line has height 0.

View on LeetCode

Hints

Hint 1

The area of a pair is min(height[i], height[j]) * (j - i).

Hint 2

Try every pair of lines.

Solution

Intuition

The area of a pair is min(height[i], height[j]) * (j - i). Two things fight each other: you want a wide pair and a tall pair. Width is easiest to reason about because it only shrinks as the two lines move toward each other.

Picture two walls of a tank with the water level limited by the shorter wall. Once a wall is shorter than the other, sliding the other wall inward only narrows the tank without raising the water, so you can drop the short wall for good.

That suggests starting with the widest pair, the first and last lines, and shrinking from there. This is the converging two pointers pattern. The question at each step is which end to give up.

Look at the shorter of the two current lines. Water can never rise above it, so its best possible partner is the farthest line, which is the other pointer you already hold. Any closer partner gives less width and no more height. So the shorter line has already shown its best result, and you can discard it for good.

The taller line is different. It might still pair with something farther inside that is also tall, so you keep it. Each step throws away one line that cannot do better, and after n - 1 steps every line has been either used or ruled out.

Watch the pattern animation

Worked example

Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49
Explanation: The lines at index 1 (height 8) and index 8 (height 7) are 7 apart. Water rises only to the shorter line, 7, so the area is 7 * 7 = 49. No other pair beats it.

Approach 1: Brute force

Try every pair of lines. For each pair, compute the area from the shorter height and the distance, and keep the largest.

This is correct because the answer is by definition the best over all pairs. It does nothing clever, so it makes a good baseline for checking faster code.

Steps

  1. Set best = 0.
  2. Loop i from 0 to n - 2.
  3. For each i, loop j from i + 1 to n - 1.
  4. Compute area = min(height[i], height[j]) * (j - i).
  5. If area > best, store it in best.
  6. Return best after both loops end.

Dry run

On [1,8,6,2,5,4,8,3,7] the code checks all 36 pairs. The best area found per i is:

  • i = 0 (height 1): the best partner is index 8, area 1 * 8 = 8.
  • i = 1 (height 8): the pairs give 6, 4, 15, 16, 40, 18, 49 for j = 2..8. The best is 49, so best = 49.
  • i = 2 (height 6): the best is j = 8 with 6 * 6 = 36.
  • i = 3 to i = 7: the best values are 10, 20, 14, 3 and so on, none above 36.

After the last pair, best = 49, which matches the expected output.

Complexity

TimeO(n^2)
SpaceO(1)

Here n is the array length. The two loops visit n * (n - 1) / 2 pairs and each pair costs constant work, so time is O(n^2). Only best and the loop counters are stored, so space is O(1). At n = 10^5 that is about 5 * 10^9 pairs, which times out.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxArea(self, height: List[int]) -> int:
        n = len(height)
        best = 0
        for i in range(n - 1):
            for j in range(i + 1, n):
                area = min(height[i], height[j]) * (j - i)
                if area > best:
                    best = area
        return best
Converging (Sorted Array Target Sum) pattern infographic for Container With Most Water

Solution pattern

Converging (Sorted Array Target Sum)

Part of Two Pointers

Approach 2: Two pointers from both endsOptimalConverging (Sorted Array Target Sum)

What's slow: the brute force re-examines pairs that can never win. For a fixed left line, every partner closer than the current right line has less width and a height capped by the left line, so those pairs are strictly worse.

The insight that fixes it: put one pointer at each end and move the pointer on the shorter line inward. The shorter line already formed its best possible container with the current far end, so you can drop it without losing the answer. Each step removes one index, so the scan ends after n - 1 steps.

When the two heights are equal, either pointer may move. Both lines are capped by the same height, and each is at its best with the current partner.

Why it is correct. The shorter line can never form a larger container with any line closer than the current far end, because width only shrinks and height is capped by it. So its best pairing has already been checked and it can be discarded safely. Each step removes one line that cannot beat the best area seen so far, so the scan never misses the optimum.

Steps

  1. Set left = 0, right = n - 1, and best = 0.
  2. While left < right, compute width = right - left.
  3. Compute area = min(height[left], height[right]) * width.
  4. Update best if area is larger.
  5. If height[left] < height[right], move left one step right. Otherwise move right one step left.
  6. Return best when the pointers meet.

Dry run

Trace on [1,8,6,2,5,4,8,3,7]. Heights hl and hr are the values under the pointers.

Stepleftrighthlhrwidthareabestmove
10817888left (1 < 7)
2188774949right (7 <= 8)
3178361849right
4168854049right (tie)
5158441649right
6148531549right
713822449right
812861649right

After step 8, right becomes 1, which equals left, so the loop stops. The function returns best = 49.

Step 1 dropped the line of height 1 right away. That line could never beat 8, because its height caps every pair it joins.

Complexity

TimeO(n)
SpaceO(1)

Here n is the array length. Each loop iteration moves exactly one pointer by one step, and the pointers start n - 1 apart and stop when they meet. So there are exactly n - 1 iterations, each doing constant work, which gives O(n) time. The only state is left, right, and best, so space is O(1).

For correctness, say height[left] <= height[right], so the current area is height[left] * (right - left). Any pair (left, k) with k < right has less width and height at most height[left], so its area is smaller. Dropping left loses no better pair. The case height[right] < height[left] is symmetric.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        best = 0
        while left < right:
            width = right - left
            area = min(height[left], height[right]) * width
            best = max(best, area)
            # The shorter line is the bottleneck, so discard it.
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        return best

Common mistakes

  • Using max(height[left], height[right]) for the water level. Water spills over the shorter wall, so the level is the min.
  • Moving the taller pointer, as in if height[left] > height[right]: left += 1. The shorter line caps every container it joins, so keeping it while narrowing the width can only lower the area. Move the shorter side.
  • Moving both pointers in one iteration. This skips pairs such as a tiny left line with a huge right line, whose partner for a later left may sit at the old right. Move one pointer per step.
  • Computing width as right - left + 1. The lines are points on the x-axis, so the distance between index 1 and index 8 is 7, not 8. Use right - left.
  • Looping with while left <= right. When the pointers meet, the pair is one line with itself and has width 0. Use left < right.
  • Mixing this up with Trapping Rain Water. Here only two lines form the container and the lines between them are ignored. Do not sum water over the inner bars.

Edge cases

  • [1,1]: the smallest input. One pair, area 1 * 1 = 1.
  • [0,0,0]: every height is 0, so every area is 0 and the answer is 0.
  • [5,5,5,5]: all heights equal. The widest pair wins with 5 * 3 = 15, and the tie rule keeps the scan correct.
  • [1,2,3,4,5] (strictly increasing): the pair (2, 4) gives 3 * 2 = 6, and (1, 4) gives 2 * 3 = 6. The maximum is 6, so check that the scan does not stop early.
  • [10000, 1, 1, ..., 1, 10000] with 10^5 entries: the answer is 10000 * 99999, about 10^9, which still fits in a 32-bit int.
  • A tall line next to a short one, [9,1]: the area is min(9,1) * 1 = 1, not 9.

Follow-ups interviewers ask

Can you prove that moving the shorter pointer never skips the best pair?
Say height[left] <= height[right]. Every pair (left, k) with k < right has width smaller than right - left and height at most height[left]. Its area is below the area of (left, right), which you already recorded, so dropping left loses nothing. The mirror case works for right.
What changes if the container may be slanted or the lines have thickness?
The area formula changes, so the greedy argument has to be checked again. With a fixed thickness per line, width becomes a linear function of index distance and the same elimination argument still holds. With slanted containers the problem is a different geometry problem and the pointer rule no longer applies.
How is this different from Trapping Rain Water?
Container With Most Water picks exactly two lines and ignores everything between them. Trapping Rain Water fills water over all bars, so each position holds water up to the lower of the tallest bar on its left and the tallest bar on its right. Both use two pointers and both move the side with the lower wall, but the quantity you add up is different.

Container With Most Water FAQ

What is the time complexity of Container With Most Water?

The two pointer solution runs in O(n) time and O(1) extra space. Each step moves one pointer, and the pointers cover n - 1 positions in total. The brute force version is O(n^2) time and O(1) space.

Why use two pointers for Container With Most Water?

The area depends on width and the shorter height. Starting at maximum width and moving the shorter side is the only move that can raise the height limit. This lets you discard one index per step with a proof that no better pair is lost, which cuts O(n^2) to O(n).

Can Container With Most Water be solved in O(1) extra space?

Yes. The two pointer solution keeps only left, right, and the best area so far. It never builds a map, stack, or sorted copy. The input array is left unmodified.

Do I need to sort the array for Container With Most Water?

No, and sorting would break the problem. The index is the x-coordinate, so reordering the heights changes which lines are next to each other. The pointers work on index order, which is already sorted by position.

What should I do when the two heights are equal?

Move either pointer. With equal heights, both lines are capped by the same value, and each is at its best with the current partner. The usual code moves right in the else branch, and the trace above does the same at step 4.

Why does the answer fit in an int in Java and C#?

The largest possible area is a height of 10^4 times a width of 10^5 minus 1, which is under 10^9. A signed 32-bit int holds up to about 2.1 * 10^9, so no overflow happens.

Asked at

See which companies ask this — Pro

Practise it