Solution: Container With the Most Water
Let's solve the Container with Most Water problem using the Two Pointers pattern.
Statement
You’re given an integer array height
of length , and there are vertical lines drawn such that the two endpoints of the line are and (, height[i]
).
Find two lines from the input array that, together with the x-axis, form a container that holds as much water as possible. Return the maximum amount of water a container can store.
Note: You may not slant the container.
Constraints:
-
height.length
-
-
height[i]
Solution
So far, you’ve probably brainstormed some approaches and have an idea of how to solve this problem. Let’s explore some of these approaches and figure out which to follow based on considerations such as time complexity and implementation constraints.
Naive approach
A naive approach to solve this problem would be to find the area of every possible pair of vertical lines and select the maximum area out of them.
The time complexity for this approach would be , where is the length of the input array. The space complexity would be , since only a constant amount of extra space is used.
Optimized approach using two pointers
An optimized approach to solve this problem is using two pointers, start
and end
, initialized at the beginning and end of the array, respectively. We also create a variable to store the maximum area and set it to zero.
While iterating through the array, height
, the algorithm proceeds through the following steps:
- Calculate the distance,
width
, between the two vertical lines pointed bystart
andend
pointer aswidth
end
start
. - The height of the container is determined by the shorter of the two vertical lines pointed by the
start
andend
pointers. Then, multiply this height by thewidth
to calculate the area of the container. - If the calculated area is greater than the current value of the maximum area, update the maximum area.
- Move the pointer pointing to the shorter vertical line inward by one step. This is because if we try to move the pointer at the longer vertical line, we won’t gain any increase in area, since the shorter line limits it.
- Keep iterating through the array until the pointers meet.
After iterating through the array, return the maximum area.
Now, let’s look at the following illustration to get a better understanding of the solution: