Container With Most Water

Find two lines that form a container holding the most water.

Pattern

Greedy Two Pointers

This problem follows the Greedy Two Pointers pattern, commonly found in the Two Pointers category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Start with widest container. Move the shorter line inward to potentially find taller ones.

Key Insight

Always move the shorter side — moving the taller side can never increase the area since the height is bounded by the shorter line.

Step-by-step

  1. 1Initialize left = 0, right = n-1, maxArea = 0
  2. 2Calculate area = min(height[left], height[right]) * (right - left)
  3. 3Update maxArea if current area is larger
  4. 4Move the pointer pointing to the shorter line inward
  5. 5Repeat until left meets right

Pseudocode

left = 0, right = n - 1, maxArea = 0
while left < right:
    area = min(height[left], height[right]) * (right - left)
    maxArea = max(maxArea, area)
    if height[left] < height[right]:
        left++
    else:
        right--
return maxArea
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
More Two Pointers Problems

Master this pattern with YeetCode

Practice Container With Most Water and similar Two Pointers problems with flashcards. Build pattern recognition through active recall.

Practice this problem