from typing import List
Problem Description
Difficulty: Medium
You are provided with an integer array height
, where each element represents the height of a vertical line at a specific index on the x-axis.
Find the two distinct lines that, along with the x-axis, form a container capable of holding the maximum amount of water.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: In this case, the maximum area of water the container can contain is 49 (7 x 7). The height of the container is 7, governed by the shorter of the two lines of height 8 and 7, and the width between these two lines is 7. The container with height 8 on both sides has a width of 5; thus an area of 40 (8 x 5), which is not the maximum possible.
Example 2:
Input: height = [2,2,2]
Output: 4
Constraints:
# NeetCode:
2 <= height.length <= 10^3
0 <= height[i] <= 10^3
# LeetCode:
2 <= height.length <= 10^5
0 <= height[i] <= 10^4
Initial Solution
class BruteForceSolution:
def maxArea(self, heights: List[int]) -> int:
= 0
max_area
for x1, y1 in enumerate(heights):
for x2, y2 in enumerate(heights):
if x1 == x2:
continue
= (x2 - x1) * min(y1, y2)
area = max(area, max_area)
max_area
return max_area
= [1,8,6,2,5,4,8,3,7]
heights1 = [2,2,2]
heights2 = BruteForceSolution()
solution assert solution.maxArea(heights1) == 49
assert solution.maxArea(heights2) == 4
class Solution:
def maxArea(self, heights: List[int]) -> int:
= 0
max_area = 0
l = len(heights) - 1
r
while l < r:
= (r - l) * min(heights[l], heights[r])
area = max(max_area, area)
max_area
if heights[l] < heights[r]:
+= 1
l else:
-= 1
r
return max_area
= [1,8,6,2,5,4,8,3,7]
heights1 = [2,2,2]
heights2 = Solution()
solution assert solution.maxArea(heights1) == 49
assert solution.maxArea(heights2) == 4
Initial Results
My inital brute force solution passed NeetCode. However, with \(O(n^2)\) time complexity, it’s insufficient for LeetCode. The next attempt was a two-pointer solution, with worst-case complexity of:
- Time complexity: \(O(n)\) as the pointers traverse the input list only once
- Space complexity: \(O(1)\) as no additional space is used that would grow with input size
NeetCode Solution
NeetCode’s solution is basically the same as that shown above. To be fair, I originally had if
, elif
, and else
statements for the <
, >
, and ==
conditions, but as the outcomes of the elif
and else
branches were exactly the same, they could be combined.