Question

Restate

  • Given an integer array height, where height[i] is the height of a vertical line at i
  • Choose two lines with x-axis, form a container
  • Find two lines that contain the most water
  • Return the maximum area

Edge Case

  • len(height) < 2
  • All equal heights (e.g., [5,5,5]) → widest pair is optimal

MethodApproachTime ComplexitySpace Complexity
Method 1 ⭐Two Pointers

Method 1 - Two Pointers

Approach

Key idea:

  • The water area is limited by the shorter line
  • To possibly increase the area, always move the pointer at the shorter line
  • Use two pointers left (start) and right (end)
  • At each step:
    1. Compute area using the current pair.
    2. Update res.
    3. Move the pointer at the shorter height inward:
      • Because width decreases no matter what; the only chance to get a bigger area is to potentially increase the limiting height min(...).
      • Moving the taller side cannot increase min(...) when the shorter side stays the same, so it can’t lead to a better area than the current width.

Complexity

  • Time Complexity:
  • Space Complexity:

Code

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        res = 0
        while left < right:
            high = min(height[right], height[left])
            area = (right - left) * high
            res = max(res, area)
            
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        
        return res

Common Mistake

  • Using while left <= right (when left == right, width is 0, no need to compute)