Container With Most Water

You are given an array height of length n. Picture n vertical walls standing on a flat floor, one unit apart: wall i stands at position i and is height[i] units tall.

Choose any two walls. Together with the floor they form an open container, and the water it holds is limited by the shorter wall: its amount is min(height[i], height[j]) * (j - i). All other walls are ignored (they do not block or split the water).

Return the largest amount of water any pair of walls can hold.

Example 1

Input: height = [3,7,2,5,4,8,6,1] Output: 30 Why: Walls at positions 1 (height 7) and 6 (height 6) hold min(7, 6) × 5 = 30 units.

Example 2

Input: height = [2,5] Output: 2 Why: With only two walls, the answer is min(2, 5) × 1 = 2.

Example 3

Input: height = [1,9,2,3,9,1] Output: 27 Why: The outermost walls are short, but positions 1 and 4 hold min(9, 9) × 3 = 27.

Constraints

  • 2 <= n <= 105
  • 0 <= height[i] <= 104

Pattern Path · Two Pointers · problem 21 of 169

Checking all pairs is O(n²). Start with the widest possible container: the first and last wall. How could a narrower container ever beat it?
When you move one of the two walls inward the width shrinks by one, so the only hope is a taller limiting wall.
Moving the taller wall inward can never help: the shorter wall still caps the height while the width drops. So always move the shorter one.
Target: O(n) time, O(1) extra space.

Start simple

Evaluate every pair of walls and keep the best: O(n²) time, O(1) space.

The key idea

Place one pointer on the first wall and one on the last, record the water between them, and then move the pointer at the shorter wall one step inward. Repeat until the pointers meet.

Why is it safe to discard the shorter wall? Say height[left] <= height[right]. Any container that uses left together with some wall between the pointers is narrower than the current one, and its height is still at most height[left]. So none of those pairs can beat what we just recorded, and left can never again be part of a better answer. Dropping it loses nothing.

Each step eliminates one wall, so after n - 1 steps every candidate pair has been either measured or proven no better than one that was. That turns an O(n²) search into a single linear sweep.

Complexity

  • Time: O(n)
  • Space: O(1)

Python

class Solution:
    def maxArea(self, height):
        left, right = 0, len(height) - 1
        best = 0
        while left < right:
            water = min(height[left], height[right]) * (right - left)
            best = max(best, water)
            # The shorter wall can never be part of a better container.
            if height[left] <= height[right]:
                left += 1
            else:
                right -= 1
        return best

JavaScript

var maxArea = function(height) {
  let left = 0, right = height.length - 1;
  let best = 0;
  while (left < right) {
    const water = Math.min(height[left], height[right]) * (right - left);
    best = Math.max(best, water);
    // The shorter wall can never be part of a better container.
    if (height[left] <= height[right]) left++;
    else right--;
  }
  return best;
};

What the interviewer is checking

The code is short; the real test is whether you can justify why moving the shorter pointer never skips the optimal pair.

Mistakes to avoid

  • Moving the taller wall, which can skip the best answer.
  • Using the taller wall (or the sum) as the water height instead of the shorter one.
  • Confusing this with trapping rain water, where the walls in between do matter.

Follow-ups to expect

  • How would you compute the total water trapped between all walls instead? (Prefix maxima or two pointers.)
  • Prove the greedy step formally. (Exchange argument on discarded pairs.)
  • What if equal heights are common, can you move both pointers? (Yes, both are dominated.)

In real software

The same shrink-the-window-from-the-weaker-side reasoning appears in optimising pairs under a min/product objective, such as picking two price points or two sensors that maximise a bottlenecked throughput times distance.

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url