← Back to Algorithms, page 1

algorithms-0018 · Medium mid

Container with most water: choose two vertical lines that, with the x-axis, hold the most water.

Start with pointers at both ends, which gives the widest container. The area is limited by the shorter line, so moving the taller line inward can never help; always move the shorter one. Track the maximum area as the pointers meet. O(n) time and O(1) space, versus O(n^2) for trying every pair.

Full answer

Problem

Given heights where line i goes from (i, 0) to (i, heights[i]), find two lines that together with the x-axis form a container holding the most water. Return the maximum area min(h[i], h[j]) x (j - i).

Example: [1, 8, 6, 2, 5, 4, 8, 3, 7] gives 49 (lines at index 1 and 8: min(8, 7) x 7).

Constraints: 2 <= len(heights) <= 10^5, heights from 0 to 10^4.

Brute force

Check every pair: O(n^2), about 5 x 10^9 pairs for 10^5 lines.

Optimal approach

  1. lo = 0, hi = n - 1, best = 0.
  2. Compute the area for lo and hi, update best.
  3. Move the pointer at the shorter line inward (either one on a tie).
  4. Stop when they meet.

Why it works

Suppose heights[lo] < heights[hi]. Any container using lo with some line k between them has width less than hi - lo and height at most heights[lo], so its area is smaller than the current one. Therefore lo cannot be part of a better answer and can be discarded. Each step discards one line that is provably not in a better pair, so after n - 1 steps every candidate has been accounted for.

Complexity

O(n) time, O(1) space.

Code

python
def max_area(heights):
    """Max water between two lines: two pointers moving the shorter side. O(n)."""
    lo, hi = 0, len(heights) - 1
    best = 0
    while lo < hi:
        width = hi - lo
        if heights[lo] < heights[hi]:
            best = max(best, heights[lo] * width)
            lo += 1
        else:
            best = max(best, heights[hi] * width)
            hi -= 1
    return best


def max_area_brute(heights):
    n = len(heights)
    return max((min(heights[i], heights[j]) * (j - i)
                for i in range(n) for j in range(i + 1, n)), default=0)


if __name__ == "__main__":
    for f in (max_area, max_area_brute):
        assert f([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
        assert f([1, 1]) == 1
        assert f([4, 3, 2, 1, 4]) == 16
        assert f([5]) == 0
        assert f([]) == 0
    print("all tests passed")

Save as a18_container_water.py and run python3 a18_container_water.py. It prints all tests passed (Python 3.13.5).

Edge cases

Two lines. Lines of height 0. All equal heights (the widest pair wins). Fewer than two lines returns 0 in this implementation.

Pattern

Opposite-end two pointers with an exchange argument: discard the side that cannot improve the answer. Compare with trapping rain water, which uses a similar pointer movement but sums water over every position.

python
def max_area(heights):
    """Max water between two lines: two pointers moving the shorter side. O(n)."""
    lo, hi = 0, len(heights) - 1
    best = 0
    while lo < hi:
        width = hi - lo
        if heights[lo] < heights[hi]:
            best = max(best, heights[lo] * width)
            lo += 1
        else:
            best = max(best, heights[hi] * width)
            hi -= 1
    return best


def max_area_brute(heights):
    n = len(heights)
    return max((min(heights[i], heights[j]) * (j - i)
                for i in range(n) for j in range(i + 1, n)), default=0)


if __name__ == "__main__":
    for f in (max_area, max_area_brute):
        assert f([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
        assert f([1, 1]) == 1
        assert f([4, 3, 2, 1, 4]) == 16
        assert f([5]) == 0
        assert f([]) == 0
    print("all tests passed")

Two-pointer solution and an O(n^2) brute force checked by the same tests.

Complexity

Time: O(n). Space: O(1). The brute force reference is O(n^2).

By level

Fresher: Writes the brute force and then the two-pointer version, explaining why the shorter line moves. Should explain the area formula with width and the shorter height.

Mid: Gives a clear exchange argument and contrasts with the rain water problem. Proves that moving the taller side can never help.

Senior: Formalises the proof, discusses variants with constraints on pairs and explains how the same discard reasoning appears in other two-pointer problems. Contrasts this problem with trapping rain water.

Key points

  • Start at both ends for maximum width
  • Area is limited by the shorter line
  • Move the shorter line inward
  • The discarded line cannot be in a better pair
  • O(n) time, O(1) space

Common mistakes

  • Moving the taller line
  • Confusing this with trapping rain water
  • Not proving why discarding is safe
  • Using area = max height times width

Follow-ups

  • Prove the discard step more formally
  • How is trapping rain water different?
  • What if you could choose three lines?

Tips

  • State the exchange argument in one sentence
  • Trace the first few steps on the example
  • Distinguish from trapping rain water

Evaluation rubric

  • Correct O(n) algorithm
  • Sound correctness argument
  • Correct area formula
  • Handles ties and small inputs