NeetCode 150 / Two Pointers

013Container With Most Water

MediumTwo PointersO(n)

Dry run

height = [1, 8, 6, 2, 5, 4, 8, 3, 7]Step 1 of 10
1
0l
8
1
6
2
2
3
5
4
4
5
8
6
3
7
7
8r
best area
0

Start with the widest container: l at the first line and r at the last. The water it holds is the shorter line times the width r − l.

Pythontime O(n) · space O(1)
1def maxArea(height):
2 l, r, best = 0, len(height) - 1, 0
3 while l < r:
4 best = max(best, min(height[l], height[r]) * (r - l))
5 if height[l] < height[r]:
6 l += 1
7 else:
8 r -= 1
9 return best
Variables
l0
r8
width—
area—
best0

Problem

You are given an integer array height of length n. Find two lines that, together with the x-axis, form a container that holds the most water. Return the maximum amount of water a container can store.

Examples

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

Lines at index 1 and 8: min(8,7) × (8 − 1) = 49

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

Only one pair exists: min(1,1) × 1 = 1

Constraints

  • n == height.length
  • 2 ≤ n ≤ 10⁵
  • 0 ≤ height[i] ≤ 10⁴

Intuition

The widest container uses the two outer lines. Moving the taller line inward can never help — the width shrinks and the height is still capped by the shorter line. So always advance the shorter side, and the area can only get a chance to grow. One pass finds the maximum.

Brute force → Optimal

Brute force

Try every pair of lines (i, j) and keep the largest min(height[i], height[j]) × (j − i).

Time O(n²)Space O(1)
Optimal

Two pointers at the ends. Compute the area, record the best, then move the pointer at the shorter line inward. This is the only move that can expose a taller wall, so a single pass is enough.

Time O(n)Space O(1)

Complexity

Time O(n)Space O(1)

Edge cases

  • Exactly two lines: the loop runs once and the answer is the shorter line times width 1.
  • All heights are zero: every area is 0, so the answer is 0.

Common mistakes

  • Moving the taller line instead of the shorter one, which can skip over the pair that yields the maximum area.
  • Using `r - l + 1` as the width; the distance between two lines at indices l and r is `r - l`.

জটিলতা

O(n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(1)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← 3Sumপরের সমস্যাTrapping Rain Water →