The problem is about finding two lines which together with the x-axis forms a container such that the container contains the most water.
A basic brute-force approach would involve checking the area for every possible pair of lines. This approach would be:
A more efficient approach is the two-pointer technique:
left
) and one at the end (right
) of the list.This approach ensures that we check every possible combination in a linear manner:
Here’s the implementation of the two-pointer technique in Python:
def maxArea(height):
left, right = 0, len(height) - 1
max_area = 0
while left < right:
# Calculate the area
width = right - left
current_height = min(height[left], height[right])
current_area = width * current_height
max_area = max(max_area, current_area)
# Move the pointer at the shorter line
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area
Let’s consider a few test cases to validate our approach:
maxArea([1,8,6,2,5,4,8,3,7])
should return 49
.maxArea([1,1])
should return 1
.maxArea([4,3,2,1,4])
should return 16
.maxArea([1,2,1])
should return 2
.Thus, the overall time complexity is (O(n)), and the space complexity is (O(1)) as we are using only a few extra variables.
Feel free to ask any further questions or let me know if there’s any other aspect you’d like to explore!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?