THN Interview Prep

011. Container With Most Water

Quick Identifier

  • Topic: two-pointers
  • Pattern: inward convergence on two boundaries
  • Difficulty: Medium
  • Companies: Amazon, Google, Meta, Bloomberg, Adobe
  • Frequency: Very High
  • LeetCode: 11
  • Hint: The shorter wall limits area. Move the shorter wall because the width only gets smaller.

Quick Sights

  • Time Complexity: O(n) - every pointer moves inward at most once per index.
  • Space Complexity: O(1) - only two indexes and the best area are stored.
  • Core Mechanism: Compute area = (right - left) * min(height[left], height[right]), update best, then move the pointer at the shorter wall.

Concept Explanation

Area is controlled by two facts: width and the shorter wall. Since width decreases on every move, the only possible way to improve the answer is to find a taller bottleneck wall.

If height[left] <= height[right], any future container that keeps left will have smaller width and a height no taller than height[left]. So left can be discarded safely. The same argument applies to right when it is shorter.

Diagram

This diagram shows the pointer decisions and the step-by-step algorithm flow.

Loading diagram…

Study Pattern (SDE3+)

  • 0-3 min: Name the pointer shape, then state the invariant and discard rule before coding.
  • Implementation pass: Keep pointer movement explicit; every branch must return, record an answer, or move at least one pointer.
  • 5 min extension: Explain how the solution changes for immutable input, streaming input, many duplicate values, or many repeated queries.

Approaches

  • Brute force all pairs is O(n^2). Sorting is invalid because index distance matters. The optimal two-pointer scan is O(n).

Optimal Solution

JavaScript

function maxArea(height) {
	let left = 0;
	let right = height.length - 1;
	let best = 0;

	while (left < right) {
		best = Math.max(best, (right - left) * Math.min(height[left], height[right]));
		if (height[left] <= height[right]) left++;
		else right--;
	}

	return best;
}

Go

func maxArea(height []int) int {
	left, right := 0, len(height)-1
	best := 0
	for left < right {
		area := (right - left) * min(height[left], height[right])
		if area > best {
			best = area
		}
		if height[left] <= height[right] {
			left++
		} else {
			right--
		}
	}
	return best
}

func min(a int, b int) int {
	if a < b {
		return a
	}
	return b
}

Walkthrough

For [1,8,6,2,5,4,8,3,7], the best container is between heights 8 and 7, width 7, area 49.

Edge Cases

  • Two lines only
  • Equal heights may move either side
  • Positions cannot be sorted away.

Pitfalls

  • Moving the taller wall
  • Using max instead of min
  • Computing width as right - left + 1.

Similar Problems

Mind-Map Tags

#two-pointers #area #inward-convergence

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page