MediumNo. 0011

Container With Most Water — LeetCode 11 Python Solution

Topics
Greedy, Array, Two Pointers
Reading time
2 min

The problem

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]).

Example

Input
height = [1,8,6,2,5,4,8,3,7]
Output
49
Explanation
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Python solution

PythonSolution
class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r = 0, len(height) - 1
        ans = 0
        while l < r:
            t = min(height[l], height[r]) * (r - l)
            ans = max(ans, t)
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
        return ans

Complexity

Time
O(n)where n is the length of the array height
Space · auxiliary
O(1)

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 11. Container With Most Water is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0455Assign CookiesEasy
0611Valid Triangle NumberMedium
0826Most Profit Assigning WorkMedium
0870Advantage ShuffleMedium
0881Boats to Save PeopleMedium
0942DI String MatchEasy

Frequently asked questions

How hard is LeetCode 11. Container With Most Water?

LeetCode 11. Container With Most Water is rated Medium on LeetCode.

What is the time complexity of LeetCode 11. Container With Most Water?

The Python solution on this page runs in O(n), where n is the length of the array \textit{height}.

What is the space complexity of LeetCode 11. Container With Most Water?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 11. Container With Most Water cover?

LeetCode 11. Container With Most Water is tagged Greedy, Array and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.