Container With Most Water (Two Pointer Approach)

Find two lines that hold the most water using two pointers from both ends, moving the shorter line inward, in O(n) time.

Problem Statement

Given heights height[i] of vertical lines, pick two lines that, with the x-axis, form a container holding the most water. Return that maximum area.

Example

Input:  height = [1,8,6,2,5,4,8,3,7]
Output: 49

Two Pointer Approach

Start with the widest container (both ends). The area is min(height[left], height[right]) * (right - left). Moving the taller line can only shrink the area, so always move the shorter line inward, hoping for a taller one.

Complexity

  • Time: O(n)
  • Space: O(1)

Solution Code

Python

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

Java

int maxArea(int[] height) {
    int left = 0, right = height.length - 1, best = 0;
    while (left < right) {
        int area = Math.min(height[left], height[right]) * (right - left);
        best = Math.max(best, area);
        if (height[left] < height[right]) left++;
        else right--;
    }
    return best;
}

C++

int maxArea(vector<int>& height) {
    int left = 0, right = height.size() - 1, best = 0;
    while (left < right) {
        int area = min(height[left], height[right]) * (right - left);
        best = max(best, area);
        if (height[left] < height[right]) left++;
        else right--;
    }
    return best;
}

Key Takeaways

  • Width shrinks every step, so only a taller line can improve the area.
  • Always discard the shorter line — it is the limiting factor.
  • Greedy two pointers turn O(n^2) brute force into O(n).
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.