ToolMight Logo
MediumTwo PointersTwo Pointers Inward ConvergenceGreedy Area Maximization

Container With Most Water

Find two vertical walls bounding maximum water volume. Compare quadratic pair enumeration against O(n) greedy two-pointer elimination.

Optimal Time
O(n)
Optimal Space
O(1)
Primary Pattern
Two Pointers Inward Convergence
Visualizer
Open Interactive View →

Problem Statement

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith 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.

Notice that you may not slant the container.

Examples & Constraints

Example 1
Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49
Explanation: The vertical lines are at index 1 (height 8) and index 8 (height 7). Width is (8 - 1) = 7. Water capacity is min(8, 7) * 7 = 49.
Example 2
Input: height = [1, 1]
Output: 1
Explanation: Width is (1 - 0) = 1. Height is min(1, 1) = 1. Area is 1 * 1 = 1.
Constraints
  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4

Pattern Recognition & Core Invariant

How to Spot This Pattern

Objective functions shaped like distance(i, j) * min(val[i], val[j]) start at maximum width (0, n - 1) and always advance whichever endpoint limits the height.

Core Invariant

At any window [left, right], moving the taller endpoint inward can only narrow width while keeping min(height) bounded by the shorter endpoint — so discarding the shorter wall never misses the global optimum.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. All-Pairs Area Enumeration (Brute Force)
O(n²)O(1)Check every pair of vertical lines (i, j) with i < j and retain the maximum (j - i) * min(height[i], height[j]).
2. Two Pointers Greedy Inward ScanOptimal
O(n)O(1)Start with pointers at both extremes (maximum width). At each step, calculate area and move the pointer with the smaller height inward to potentially find a taller bottleneck in O(n) time.

1. All-Pairs Area Enumeration (Brute Force)

TimeO(n²)
SpaceO(1)

Check every pair of vertical lines (i, j) with i < j and retain the maximum (j - i) * min(height[i], height[j]).

Time ComplexityO(n²)

Nested loops evaluate n(n - 1) / 2 pairs.

Space ComplexityO(1)

Scalar loop indices and maxArea only.

How It Works

Exhaustive Pair Checking

Every candidate container is defined by a left index i and a right index j > i. Computing (j - i) * min(height[i], height[j]) over all n(n - 1) / 2 pairs guarantees finding the global optimum in O(1) space, but times out once n reaches 10^5.

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Pairs Starting at i = 0 (height 1)

Best area paired with index 0 reaches width 8 * min(1, 7) = 8.

State:i = 0 -> maxWater = 8
Strengths
  • +Trivial correctness without needing a pruning proof
  • +Constant O(1) auxiliary space
Trade-offs
  • -Quadratic O(n²) runtime exceeds time limits at n = 10^5

Reference Implementation

Complete implementation for All-Pairs Area Enumeration (Brute Force) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def max_area_brute(height: list[int]) -> int:
best = 0
n = len(height)
for i in range(n):
for j in range(i + 1, n):
best = max(best, (j - i) * min(height[i], height[j]))
return best

2. Two Pointers Greedy Inward Scan

Optimal
TimeO(n)
SpaceO(1)

Start with pointers at both extremes (maximum width). At each step, calculate area and move the pointer with the smaller height inward to potentially find a taller bottleneck in O(n) time.

Time ComplexityO(n)

Each iteration moves either the left or right pointer by one position inward. The loop runs at most N - 1 times.

Space ComplexityO(1)

Operates strictly in-place with two integer index variables and a running maximum variable.

How It Works

The Mathematical Formula

The volume of water between two vertical lines at indices left and right is:
area = (right - left) * min(height[left], height[right])

Here, (right - left) is the width, and the shorter line is the limiting bottleneck.


The Greedy Choice: Why Discard the Shorter Line?

Suppose height[left] < height[right]:

  • If we keep left and move right inward to right - 1, the width will decrease by 1.
  • What about the height? The new height is bounded by min(height[left], height[right - 1]), which can never exceed height[left].
  • Decreased width equal or smaller height = strictly smaller area*!

Therefore, keeping the shorter line left while moving right inward can never yield a larger area than what we have already evaluated. We can safely discard left and advance left++!

By moving the pointer at the shorter line inward at every step:

  1. We start with the maximum possible width (left = 0, right = n - 1).
  2. We evaluate the current area and update maxArea.
  3. We advance the pointer with the smaller height.
  4. When left >= right, we have proven that no container can exceed maxArea.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Initial Boundaries

left = 0 (height 1), right = 8 (height 7). Width = 8. Area = min(1, 7) * 8 = 8. maxArea = 8.

State:left = 0 (1)right = 8 (7) -> area: 8
Strengths
  • +Optimal O(n) single pass runtime
  • +O(1) auxiliary space without mutating the input
Trade-offs
  • -Greedy elimination proof can be unintuitive to prove during interview without width/height bounding logic

Reference Implementation

Complete implementation for Two Pointers Greedy Inward Scan in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def max_area(height: list[int]) -> int:
left = 0
right = len(height) - 1
max_water = 0
while left < right:
current_width = right - left
current_height = min(height[left], height[right])
current_water = current_width * current_height
if current_water > max_water:
max_water = current_water
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_water
if __name__ == "__main__":
test1 = [1, 8, 6, 2, 5, 4, 8, 3, 7]
test2 = [1, 1]
print("test1 max area:", max_area(test1))
print("test2 max area:", max_area(test2))
Interactive Visualizer

Trace Array & Matrix mechanics in memory

Step through custom inputs in the Array & Matrix visualizer to inspect pointer updates, array shifts, and call-stack state alongside Container With Most Water.

Open Array & Matrix visualizer

Frequently Asked Questions

Why does moving the taller line inward never help?

Area equals width * min(left, right). Keeping the shorter side fixed while moving the taller side inward strictly decreases width while min(left, right) stays capped at the shorter wall — so area can never beat what we already computed.

What if both lines have equal height?

When height[left] == height[right], moving either pointer (or both, if distinct widths matter cleanly one at a time) is valid because any larger rectangle would strictly require both endpoints inward to be taller than the equal edge anyway.

How is this different from Trapping Rain Water?

Container With Most Water picks two boundary walls ignoring intermediate bars inside (width * min(h[l], h[r])), whereas Trapping Rain Water fills every unit column above intermediate bars (sum min(leftMax, rightMax) - height[i]).

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Minimum length array (n = 2, e.g. [0, 5] -> 0 or [1, 1] -> 1).
  • Container containing a zero-height wall returns 0 area for pairs involving that wall.
  • Uniform heights ([5, 5, 5, 5]) immediately achieve global maximum at the widest boundary (0, n - 1).

Common Bugs to Avoid

  • Advancing the taller pointer instead of the shorter pointer.
  • Looking ahead greedily one step (`height[left + 1] > height[right - 1]`), which breaks because nearby bars don't decide global optima.
  • Mixing up Container With Most Water (pick 2 outer walls ignoring bars between) with Trapping Rain Water (accumulate water per bar).

Interview Follow-Up Variations

  • Explain formally why equal heights (`height[left] == height[right]`) allow advancing either pointer (or both) without missing a stricter maximum.
  • Contrast with Trapping Rain Water (LeetCode 42), which requires prefix/suffix height envelopes instead of a single two-wall rectangle.

Related Problems

All problems
MediumTwo Pointers

3Sum

Find all unique integer triplets summing to zero. Compare hash-set pair lookup against sorting + two-pointer inward scans with duplicate skipping.

Pattern: Sort then Two Pointers
O(n²) · O(1) to O(n)
Solve
EasyTwo Pointers

Valid Palindrome

Check whether a string reads identically forward and backward over alphanumeric characters. Compare build-and-reverse against O(1)-space converging pointers.

Pattern: Two Pointers Converging
O(n) · O(1)
Solve
HardTwo Pointers

Trapping Rain Water

Calculate total trapped water between elevation bars. Compare O(n)-space prefix/suffix max arrays with O(1)-space converging two pointers.

Pattern: Two Pointers Max Boundaries
O(n) · O(1)
Solve