↓Skip to main content
  1. LeetCode/

LeetCode 11: Container With Most Water

·2 mins· ·
LeetCode Medium Array Two-Pointers Greedy
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-20

  • Submissions: Runtime Error → Time Limit Exceeded → Accepted ×6 → Wrong Answer ×2 → Accepted

Approach
#

The area is width × the shorter height (Two Pointers Template 1). Starting at both ends maximizes width. Each step moves one side:

  • Moving the taller side narrows the width while the shorter side still caps the height, so the area cannot grow.
  • So move the shorter side, the only chance of finding something taller.

My Attempts
#

A November 2022 rewrite wrote if r > l: l += 1, testing positions rather than heights, so it always moved left: [3, 5, 1] should be 3 (between 3 and 5); it returned 2.

Solution
#

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

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Choose which side to move by height, not position.

Interview Explanation
#

From both ends I compute the area and move the shorter side, since moving the taller one only reduces width without raising the height. Each position is seen once, O(n).

Related

LeetCode 15: 3Sum
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 15 note: sort, fix the first number, and find the other two with converging pointers, skipping equal values at all three positions to avoid duplicate triplets
LeetCode 16: 3Sum Closest
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 16 note: sort, fix one number, and find the other two with converging pointers, comparing the distance abs(sum - target)
LeetCode 18: 4Sum
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 18 note: sort, fix the first two numbers with two loops, and converge pointers for the rest, skipping equal values at all four positions
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 942: DI String Match
·1 min
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 note: two pointers hold the smallest and largest unused values; place the smallest on I and the largest on D
LeetCode 19: Remove Nth Node From End of List
·2 mins
LeetCode Medium Linked-List Two-Pointers
LeetCode 19 note: from a dummy, move fast n + 1 steps ahead, then move both to the end; slow stops before the node to delete