Container With Most Water - Problem

Imagine you're designing a water collection system using vertical walls! You're given an array of n positive integers representing the height of vertical lines positioned at equal distances along the x-axis.

Each line i extends from point (i, 0) to (i, height[i]). Your goal is to find two lines that, together with the x-axis, form a container that can hold the maximum amount of water.

Key Rules:

  • The container cannot be tilted (must be upright)
  • Water level is limited by the shorter of the two walls
  • The wider the container, the more water it can potentially hold
  • Return the maximum area of water that can be contained

Formula: Area = min(height[i], height[j]) ร— (j - i)

Input & Output

example_1.py โ€” Standard Case
$ Input: [1,8,6,2,5,4,8,3,7]
โ€บ Output: 49
๐Ÿ’ก Note: The maximum area is between lines at indices 1 and 8 (heights 8 and 7). Area = min(8,7) ร— (8-1) = 7 ร— 7 = 49.
example_2.py โ€” Minimal Case
$ Input: [1,1]
โ€บ Output: 1
๐Ÿ’ก Note: Only two lines available, both with height 1. Area = min(1,1) ร— (1-0) = 1 ร— 1 = 1.
example_3.py โ€” Ascending Heights
$ Input: [2,3,4,5,18,17,6]
โ€บ Output: 17
๐Ÿ’ก Note: Maximum area is between indices 4 and 5 (heights 18 and 17). Area = min(18,17) ร— (5-4) = 17 ร— 1 = 17.

Visualization

Tap to expand
Container With Most Water - Visual SolutionMaximum ContainerArea = min(8,8) ร— 5 = 40Left Wall (Height: 8)Right Wall (Height: 8)Two pointers technique finds optimal solution in O(n) time
Understanding the Visualization
1
Set Up Walls
Visualize vertical lines as walls that can contain water
2
Start Wide
Begin with leftmost and rightmost walls (maximum width)
3
Move Strategically
Always move the pointer at the shorter wall inward
4
Find Maximum
Continue until pointers meet, tracking maximum area
Key Takeaway
๐ŸŽฏ Key Insight: Always move the pointer at the shorter wall because moving the taller wall would only decrease the total area while reducing width.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

We check all possible pairs of lines, which gives us nร—(n-1)/2 combinations

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track maximum area and current calculations

n
2n
โœ“ Linear Space

Constraints

  • n == height.length
  • 2 โ‰ค n โ‰ค 105
  • 0 โ‰ค height[i] โ‰ค 104
  • At least two lines are always provided
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 28 Apple 22
67.9K Views
Very High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen