Skip to main content

Container With Most Water

LeetCode 11 | Difficulty: Medium​

Medium

Problem Description​

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i^th 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.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

Input: height = [1,1]
Output: 1

Constraints:

- `n == height.length`

- `2 <= n <= 10^5`

- `0 <= height[i] <= 10^4`

Topics: Array, Two Pointers, Greedy


Approach​

Two Pointers​

Use two pointers to traverse the array, reducing the search space at each step. This avoids the need for nested loops, bringing complexity from O(nΒ²) to O(n) or O(n log n) if sorting is involved.

When to use

Array is sorted or can be sorted, and you need to find pairs/triplets that satisfy a condition.

Greedy​

At each step, make the locally optimal choice. The challenge is proving the greedy choice leads to a global optimum. Look for: can I sort by some criterion? Does choosing the best option now ever hurt future choices?

When to use

Interval scheduling, activity selection, minimum coins (certain denominations), Huffman coding.


Solutions​

Solution 1: C# (Best: 120 ms)​

MetricValue
Runtime120 ms
Memory25.5 MB
Date2019-03-19
Solution
public class Solution {
public int MaxArea(int[] height) {
int area = 0;
int i = 0, j = height.Length - 1;
while (i < j)
{
int h = Math.Min(height[i], height[j]);
area = Math.Max(area, (j-i)*h);
if(height[i]<height[j])
{
i++;

}
else
{
j--;
}

}

return area;
}
}
πŸ“œ 1 more C# submission(s)

Submission (2017-10-28) β€” 192 ms, N/A​

public class Solution {
public int MaxArea(int[] height) {
int area = 0;
int i = 0, j = height.Length - 1;
while (i < j)
{
int h = Math.Min(height[i], height[j]);
area = Math.Max(area, (j-i)*h);
while (height[i] <= h && i < j)
{
i++;
}
while (height[j] <= h && i < j)
{
j--;
}
}

return area;
}
}

Complexity Analysis​

ApproachTimeSpace
Two Pointers$O(n)$$O(1)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Ask: "Can I sort the array?" β€” Sorting often enables two-pointer techniques.
  • LeetCode provides 3 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: If you simulate the problem, it will be O(n^2) which is not efficient.

Hint 2: Try to use two-pointers. Set one pointer to the left and one to the right of the array. Always move the pointer that points to the lower line.

Hint 3: How can you calculate the amount of water at each step?