Skip to main content
11

Container With Most Water

Mediumtwo pointersgreedy

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Two PointersRead the beginner guide

You're given an array height of n vertical lines: line i stands at position i and is height[i] tall.

Pick two lines. Together with the floor they form a container. Return the most water a container can hold.

Understand the problem

Picture the lines as walls standing on the floor. Pick any two walls and pour water between them:

  • The water width is the distance between the two walls: right - left.
  • The water height is the height of the shorter wall. Any higher and the water would spill over it.
  • So the amount of water is width × min(height[left], height[right]).

The walls in between don't matter: they don't block anything, the water just fills around them.

Example 1

text
Input:  height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49

Pick the wall at index 1 (height 8) and the wall at index 8 (height 7):

  • width = 8 - 1 = 7
  • height = the shorter wall = 7
  • water = 7 × 7 = 49. No other pair holds more.

Example 2

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

Width 1, height 1, water 1.

Example 3

text
Input:  height = [4, 3, 2, 1, 4]
Output: 16

The two outer walls are both 4 tall and 4 apart: 4 × 4 = 16.

Constraints

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

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Start with the widest container (first and last wall), and keep moving the shorter wall inward, remembering the best area you see.

    The naive approach (and why it's slow)

    Try every pair of walls and compute the water for each. With n walls that's about n × n / 2 pairs, O(n²). For 100,000 walls that's 5 billion pairs, way too slow.

    The key insight

    Start with the widest container: left = 0, right = n - 1. Now we want to move one pointer inward. Moving inward always makes the container narrower, so the only way to get more water is to find a taller water level.

    The water level is capped by the shorter wall. Say the left wall is the shorter one:

    • If we move the taller (right) wall inward: the width shrinks, and the water is still capped by that same short left wall. The area can only go down. Useless.
    • If we move the shorter (left) wall inward: the width shrinks, but we might find a taller wall that raises the cap. This is the only move with a chance.

    So in fact, the short wall has already done its best: paired with the farthest possible partner, it produced the area we just recorded. We can throw it away for good. Every step throws away one wall, so one pass is enough.

    Step by step

    height = [1, 8, 6, 2, 5, 4, 8, 3, 7]:

    left (height)right (height)WidthWater levelAreaBestMove
    0 (1)8 (7)8188left is shorter → left++
    1 (8)8 (7)774949right is shorter → right--
    1 (8)7 (3)631849right--
    1 (8)6 (8)584049equal → right--
    1 (8)5 (4)441649right--
    1 (8)4 (5)351549right--
    1 (8)3 (2)22449right--
    1 (8)2 (6)16649right--

    The pointers meet. Answer: 49.

    When both walls are equal, moving either one is fine: the next container is capped by at most that same height and is narrower, so neither wall can do better with a new partner.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). Each step moves one pointer inward, so there are at most n - 1 steps.
    • Memory: O(1). Just two pointers and the best area.

    Common mistakes

    • Moving the taller wall. It feels natural to "keep the tall one", but you're keeping the wrong one: the short wall is the one that limits you.
    • Using the taller wall as the water height. Water spills over the shorter wall, so the height is min(...), not max(...).
    • Confusing this with "Trapping Rain Water". There, the walls in between matter. Here they don't: only the two chosen walls count.

    Going deeper

    This is a greedy argument: at each step we make a choice (drop the shorter wall) and prove it can never lose the best answer. Being able to explain why the move is safe is exactly what interviewers look for in this problem.

    Reference solution

    js
    /**
     * @param {number[]} height
     * @return {number}
     */
    export default function maxArea(height) {
      // Start with the widest container: the first and last walls.
      let left = 0
      let right = height.length - 1
      let best = 0
      while (left < right) {
        // Water = width × the SHORTER wall (any higher and it spills over).
        best = Math.max(best, (right - left) * Math.min(height[left], height[right]))
        // The shorter wall can't do better with any closer partner, so drop it.
        if (height[left] < height[right]) left++
        else right--
      }
      return best
    }
    ts
    export default function maxArea(height: number[]): number {
      // Start with the widest container: the first and last walls.
      let left = 0
      let right = height.length - 1
      let best = 0
      while (left < right) {
        // Water = width × the SHORTER wall (any higher and it spills over).
        best = Math.max(best, (right - left) * Math.min(height[left], height[right]))
        // The shorter wall can't do better with any closer partner, so drop it.
        if (height[left] < height[right]) left++
        else right--
      }
      return best
    }
    python
    def max_area(height: list[int]) -> int:
        # Start with the widest container: the first and last walls.
        left, right = 0, len(height) - 1
        best = 0
        while left < right:
            # Water = width × the SHORTER wall (any higher and it spills over).
            best = max(best, (right - left) * min(height[left], height[right]))
            # The shorter wall can't do better with any closer partner, so drop it.
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        return best