MEDIUM NC#13 Blind #10 Two Pointers
11. Container With Most Water
๐ 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]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขIn-place array updates
- โขSorted array traversal
- โขBoundary condition checks
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Two Pointers reasoning pattern
๐ก Approach
- โ Use two pointers at both ends
- โ Area = min(height[left], height[right]) * (right - left)
- โ Move the pointer with smaller height inward
- โ The goal is to find taller lines that are farther apart
- โ Time: O(n), Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse two pointers at both ends
- โขArea = min(height[left], height[right]) * (right - left)
- โขMove the pointer with smaller height inward
Common Pitfalls
- โขThe goal is to find taller lines that are farther apart
- โขTime: O(n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
maxArea([1,8,6,2,5,4,8,3,7]); Expected:
49 Test Case 2
Not run Input:
maxArea([1,1]); Expected:
1 Test Case 3
Not run Input:
maxArea([4,3,2,1,4]); Expected:
16 ๐ Code Editor
๐ค Output