Skip to main content

Container With Most Water in Python: Optimal Two Pointer Solution Explained

Problem Overview

In the Container With Most Water problem, you are given an array where each element represents the height of a vertical line drawn at that index. The goal is to find two lines that, together with the x-axis, form a container capable of holding the maximum amount of water.

Problem Visualization

Each value in the array represents a vertical line. The water trapped between any two lines depends on the distance between them (width) and the shorter of the two lines (height).

Container With Most Water Visualization - Source Leetcode #source - Leetcode

In the diagram above, the highlighted lines form the container that holds the maximum water. Even though some lines are taller, the distance between them is smaller, resulting in less area.

Key Insight

The amount of water a container can store is calculated using:


area = min(height[left], height[right]) × (right - left)
  

As the pointers move inward, the width always decreases. Therefore, the only way to potentially increase the area is by increasing the limiting height — the smaller of the two heights.

Optimal Strategy: Two Pointer Technique

To avoid checking every possible pair, we use two pointers:

  • One pointer at the beginning of the array
  • One pointer at the end of the array

At each step, the area is calculated, and the pointer pointing to the shorter line is moved inward. This greedy decision is safe because the shorter line is the bottleneck for the current container.

Algorithm Steps

  1. Initialize two pointers at the start and end of the array.
  2. Calculate the area formed by the lines at both pointers.
  3. Update the maximum area if the current area is larger.
  4. Move the pointer with the smaller height inward.
  5. Repeat until the pointers meet.

Python Implementation


class Solution:
    def maxArea(self, height: List[int]) -> int:
        l = 0
        r = len(height) - 1
        max_area = 0

        while l < r:
            current_area = min(height[l], height[r]) * (r - l)
            max_area = max(max_area, current_area)

            if height[l] < height[r]:
                l += 1
            else:
                r -= 1

        return max_area
  

Why This Approach Works

This method works because moving the taller line cannot improve the area — the height of the container is limited by the shorter line. By always moving the limiting pointer, we ensure that every move has the potential to increase the container height while accepting a reduced width.

Complexity Analysis

  • Time Complexity: O(n), where n is the number of lines.
  • Space Complexity: O(1), as no extra space is used.

Pattern Summary

This problem is a classic example of a greedy two-pointer approach. It combines pair-based decision-making with a monotonic property (shrinking width) and a clear limiting factor (minimum height), allowing an optimal linear-time solution.

Understanding this pattern helps solve many optimization problems where checking all combinations is unnecessary and inefficient.

Comments

Popular posts from this blog

LeetCode 88 Explained: Four Approaches, Mistakes, Fixes & the Final Optimal Python Solution

Evolving My Solution to “Merge Sorted Array” A practical, beginner-friendly walkthrough showing four versions of my code (from a naive approach to the optimal in-place two-pointer solution). Includes explanations, complexity and ready-to-paste code. Problem Summary You are given two sorted arrays: nums1 with size m + n (first m are valid) nums2 with size n Goal: Merge nums2 into nums1 in sorted order in-place . Version 1 — Beginner Approach (Extra List) I merged into a new list then copied back. Works, but not in-place and uses extra memory. class Solution: def merge(self, nums1, m, nums2, n): result = [] p1 = 0 p2 = 0 for _ in range(m+n): if p1 >= m: result.extend(nums2[p2:n]) break elif p2 >= n: result.extend(nums1[p1:m]) break elif nu...

Introducing CodeMad: Your Ultimate Universal IDE with Custom Shortcuts

Introducing CodeMad: Your Ultimate Multi-Language IDE with Custom Shortcuts Welcome to the world of CodeMad, your all-in-one Integrated Development Environment (IDE) that simplifies coding and boosts productivity. Developed in Python, CodeMad is designed to make your coding experience smoother and more efficient across a variety of programming languages, including C, C++, Java, Python, and HTML. Whether you're a beginner or an experienced programmer, CodeMad is your go-to tool. In this blog, we'll dive deep into the workings of CodeMad, highlighting its unique features and easy installation process. The Power of Shortcuts CodeMad's intuitive interface is built around a set of powerful keyboard shortcuts that make coding a breeze. Here are some of the key shortcuts you'll find in CodeMad: Copy (Ctrl+C) : Duplicate text with ease. Paste (Ctrl+V) : Quickly insert copied content into your code. Undo (Ctrl+Z) and Redo (Ctrl+Y) : Correct mistakes and s...

Product of Array Except Self in Python | Prefix & Suffix Explained (LeetCode 238)

Problem Overview The Product of Array Except Self is a classic problem that tests your understanding of array traversal and optimization. The task is simple to state but tricky to implement efficiently. Given an integer array nums , you need to return an array such that each element at index i is equal to the product of all the elements in nums except nums[i] . The challenge is that: Division is not allowed The solution must run in O(n) time Initial Thoughts At first glance, it feels natural to compute the total product of the array and divide it by the current element. However, this approach fails because division is forbidden and handling zeroes becomes messy. This pushed me to think differently — instead of excluding the current element, why not multiply everything around it? That’s where the prefix and suffix product pattern comes in. Key Insight: Prefix & Suffix Products For every index i : Prefix product → product of all elements to t...