Coders Crushby Napplied AI
Back to DSA Problems
MediumLeetCode #11Two Pointers

Container With Most Water

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.

Constraints
n == height.length, 2 <= n <= 10^5, 0 <= height[i] <= 10^4
Examples
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Solution Approach

Use two pointers from opposite ends converging towards each other. Compare elements at current positions and move pointers based on the comparison. Common pattern: one pointer at start, one at end, adjust based on condition.

Implementation
def maxArea(height):
    max_area = 0
    left, right = 0, len(height) - 1
    while left < right:
        width = right - left
        current_area = width * min(height[left], height[right])
        max_area = max(max_area, current_area)
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return max_area
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
Key Learning Points
Use two pointers converging from endsGreedy approach: move smaller height pointerTrack maximum area during traversal
Related Problems to Practice
3SumSort ColorsValid Palindrome
Complexity
Time:O(n)
Space:O(1)
Hints
  • 1.Area is limited by the shorter line
  • 2.Start with widest container
  • 3.Moving shorter line might find taller one
Asked at
Google
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless

Amazon
Meta
Apple
Microsoft
Goldman Sachs