LeetCode 11: Container With Most Water — Python Solution

Solve LeetCode 11: Container With Most Water in Python with a greedy boundary movement approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicTwo Pointers
Reusable patterngreedy boundary movement
ComplexityO(n) time and O(1) extra space

What the problem is testing

Measure the area between the endpoints, then move the shorter wall because keeping it cannot improve area at a smaller width.

Algorithm

  1. Measure the area between the endpoints, then move the shorter wall because keeping it cannot improve area at a smaller width.
  2. Maintain this invariant: The best area using every discarded shorter boundary has already been considered.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

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

Why this is correct

The proof follows the maintained state: The best area using every discarded shorter boundary has already been considered. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Equal walls may move either side; width decreases each iteration.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 167. Two Sum II – Input Array Is Sorted · Next: 15. 3Sum