🚀 Phases 1–5 are live — Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap →

Container With Most Water medium

Description

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i-th line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Examples

> Case 1:
    height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
    Output: 49
    Explanation: lines at indices 1 and 8 (heights 8 and 7) form a container
                 of width 7 and bottleneck height 7 → area = 49.
 
> Case 2:
    height = [1, 1]
    Output: 1

Constraints

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

State design

  1. Flavor? Opposite-ends.
  2. Pointers? l = 0, r = n - 1. Width is r - l, height is min(height[l], height[r]).
  3. Movement? Move the shorter side inward. Moving the taller side can only decrease the bottleneck (the shorter line stays the bottleneck) while shrinking the width — strictly worse. The shorter line is the only direction with hope.
  4. Stop? When l >= r.
  5. Record? Max area at every step.

Code

The convergence proof: suppose height[l] <= height[r]. The current bottleneck is height[l]. If we move r inward instead of l, the new bottleneck is min(height[l], height[r']) — still at most height[l] since r' is now smaller-indexed. The width strictly shrinks. So the area can only go down. The only direction with hope of a larger area is moving l. Symmetric if height[r] < height[l].

A tie-breaking note

When height[l] == height[r], it doesn’t matter which side we move — both produce identical optimal values. Many solutions move l by default; some move both. Either is correct.

Analysis

  • Time: O(n). Each pointer moves at most n - 1 times.
  • Space: O(1).

Same skin

  • Trapping Rain Water — similar opposite-ends idea, but tracking running max heights on each side.
  • Maximize Distance to Closest Person — opposite-ends-style scan for the largest gap.
  • Boats to Save People — opposite-ends greedy pairing for “lightest + heaviest fit in one boat?”