15% off all plans & roadmaps Use code
See plansContainer With Most Water
- LeetCode 11
- Medium
- Two Pointers
- Converging (Sorted Array Target Sum)
Updated
TL;DR: Pick two vertical lines so that the shorter height times the distance between them is as large as possible. Start with the widest pair and always move the pointer on the shorter line inward. This finds the answer in one O(n) pass.
Problem
You are given an integer array height of length n. The array describes n vertical lines: line i runs from (i, 0) up to (i, height[i]).
Choose two lines that, together with the x-axis, form a container holding as much water as possible. Return the maximum amount of water such a container can store. The container cannot be tilted.
Example 1
Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The lines are drawn from the array [1,8,6,2,5,4,8,3,7]. The best container uses the lines of height 8 and 7, and holds 49 units of water.
Example 2
Input: height = [1,1] Output: 1
Constraints
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4
Constraints that matter
- n up to 10^5 means an O(n^2) pair check does about 5 * 10^9 pair evaluations, which is too slow. You need roughly O(n) or O(n log n).
- height[i] up to 10^4 and width up to 10^5 give a largest area of 10^9, which fits in a 32-bit signed int. No long type is needed.
- n is at least 2, so there is always one valid pair and the loop never starts with an empty window.
- height[i] can be 0, so an area of 0 is a legal answer when every line has height 0.
Hints
Hint 1
The area of a pair is min(height[i], height[j]) * (j - i).
Hint 2
Try every pair of lines.
Solution
Intuition
The area of a pair is min(height[i], height[j]) * (j - i). Two things fight each other: you want a wide pair and a tall pair. Width is easiest to reason about because it only shrinks as the two lines move toward each other.
Picture two walls of a tank with the water level limited by the shorter wall. Once a wall is shorter than the other, sliding the other wall inward only narrows the tank without raising the water, so you can drop the short wall for good.
That suggests starting with the widest pair, the first and last lines, and shrinking from there. This is the converging two pointers pattern. The question at each step is which end to give up.
Look at the shorter of the two current lines. Water can never rise above it, so its best possible partner is the farthest line, which is the other pointer you already hold. Any closer partner gives less width and no more height. So the shorter line has already shown its best result, and you can discard it for good.
The taller line is different. It might still pair with something farther inside that is also tall, so you keep it. Each step throws away one line that cannot do better, and after n - 1 steps every line has been either used or ruled out.
Worked example
Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7] Output: 49 Explanation: The lines at index 1 (height 8) and index 8 (height 7) are 7 apart. Water rises only to the shorter line, 7, so the area is 7 * 7 = 49. No other pair beats it.
Approach 1: Brute force
Try every pair of lines. For each pair, compute the area from the shorter height and the distance, and keep the largest.
This is correct because the answer is by definition the best over all pairs. It does nothing clever, so it makes a good baseline for checking faster code.
Steps
- Set
best = 0. - Loop
ifrom 0 to n - 2. - For each
i, loopjfromi + 1to n - 1. - Compute
area = min(height[i], height[j]) * (j - i). - If
area > best, store it inbest. - Return
bestafter both loops end.
Dry run
On [1,8,6,2,5,4,8,3,7] the code checks all 36 pairs. The best area found per i is:
i = 0(height 1): the best partner is index 8, area 1 * 8 = 8.i = 1(height 8): the pairs give 6, 4, 15, 16, 40, 18, 49 forj = 2..8. The best is 49, sobest = 49.i = 2(height 6): the best isj = 8with 6 * 6 = 36.i = 3toi = 7: the best values are 10, 20, 14, 3 and so on, none above 36.
After the last pair, best = 49, which matches the expected output.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Here n is the array length. The two loops visit n * (n - 1) / 2 pairs and each pair costs constant work, so time is O(n^2). Only best and the loop counters are stored, so space is O(1). At n = 10^5 that is about 5 * 10^9 pairs, which times out.
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxArea(self, height: List[int]) -> int:
n = len(height)
best = 0
for i in range(n - 1):
for j in range(i + 1, n):
area = min(height[i], height[j]) * (j - i)
if area > best:
best = area
return bestJavaTested in our runner
import java.util.*;
class Solution {
public int maxArea(int[] height) {
int n = height.length;
int best = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int area = Math.min(height[i], height[j]) * (j - i);
if (area > best) {
best = area;
}
}
}
return best;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
int best = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int area = min(height[i], height[j]) * (j - i);
if (area > best) {
best = area;
}
}
}
return best;
}
};JavaScriptTested in our runner
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {
const n = height.length;
let best = 0;
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
const area = Math.min(height[i], height[j]) * (j - i);
if (area > best) {
best = area;
}
}
}
return best;
};GoTested in our runner
func maxArea(height []int) int {
n := len(height)
best := 0
for i := 0; i < n-1; i++ {
for j := i + 1; j < n; j++ {
h := height[i]
if height[j] < h {
h = height[j]
}
area := h * (j - i)
if area > best {
best = area
}
}
}
return best
}C#Tested in our runner
public class Solution {
public int maxArea(int[] height) {
int n = height.Length;
int best = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int area = Math.Min(height[i], height[j]) * (j - i);
if (area > best) {
best = area;
}
}
}
return best;
}
}
Solution pattern
Converging (Sorted Array Target Sum)
Part of Two Pointers
Approach 2: Two pointers from both endsOptimalConverging (Sorted Array Target Sum)
What's slow: the brute force re-examines pairs that can never win. For a fixed left line, every partner closer than the current right line has less width and a height capped by the left line, so those pairs are strictly worse.
The insight that fixes it: put one pointer at each end and move the pointer on the shorter line inward. The shorter line already formed its best possible container with the current far end, so you can drop it without losing the answer. Each step removes one index, so the scan ends after n - 1 steps.
When the two heights are equal, either pointer may move. Both lines are capped by the same height, and each is at its best with the current partner.
Why it is correct. The shorter line can never form a larger container with any line closer than the current far end, because width only shrinks and height is capped by it. So its best pairing has already been checked and it can be discarded safely. Each step removes one line that cannot beat the best area seen so far, so the scan never misses the optimum.
Steps
- Set
left = 0,right = n - 1, andbest = 0. - While
left < right, computewidth = right - left. - Compute
area = min(height[left], height[right]) * width. - Update
bestifareais larger. - If
height[left] < height[right], moveleftone step right. Otherwise moverightone step left. - Return
bestwhen the pointers meet.
Dry run
Trace on [1,8,6,2,5,4,8,3,7]. Heights hl and hr are the values under the pointers.
| Step | left | right | hl | hr | width | area | best | move |
|---|---|---|---|---|---|---|---|---|
| 1 | 0 | 8 | 1 | 7 | 8 | 8 | 8 | left (1 < 7) |
| 2 | 1 | 8 | 8 | 7 | 7 | 49 | 49 | right (7 <= 8) |
| 3 | 1 | 7 | 8 | 3 | 6 | 18 | 49 | right |
| 4 | 1 | 6 | 8 | 8 | 5 | 40 | 49 | right (tie) |
| 5 | 1 | 5 | 8 | 4 | 4 | 16 | 49 | right |
| 6 | 1 | 4 | 8 | 5 | 3 | 15 | 49 | right |
| 7 | 1 | 3 | 8 | 2 | 2 | 4 | 49 | right |
| 8 | 1 | 2 | 8 | 6 | 1 | 6 | 49 | right |
After step 8, right becomes 1, which equals left, so the loop stops. The function returns best = 49.
Step 1 dropped the line of height 1 right away. That line could never beat 8, because its height caps every pair it joins.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the array length. Each loop iteration moves exactly one pointer by one step, and the pointers start n - 1 apart and stop when they meet. So there are exactly n - 1 iterations, each doing constant work, which gives O(n) time. The only state is left, right, and best, so space is O(1).
For correctness, say height[left] <= height[right], so the current area is height[left] * (right - left). Any pair (left, k) with k < right has less width and height at most height[left], so its area is smaller. Dropping left loses no better pair. The case height[right] < height[left] is symmetric.
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxArea(self, height: List[int]) -> int:
left, right = 0, len(height) - 1
best = 0
while left < right:
width = right - left
area = min(height[left], height[right]) * width
best = max(best, area)
# The shorter line is the bottleneck, so discard it.
if height[left] < height[right]:
left += 1
else:
right -= 1
return bestJavaTested in our runner
import java.util.*;
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int best = 0;
while (left < right) {
int width = right - left;
int area = Math.min(height[left], height[right]) * width;
best = Math.max(best, area);
// The shorter line is the bottleneck, so discard it.
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = (int)height.size() - 1;
int best = 0;
while (left < right) {
int width = right - left;
int area = min(height[left], height[right]) * width;
best = max(best, area);
// The shorter line is the bottleneck, so discard it.
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}
};JavaScriptTested in our runner
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {
let left = 0;
let right = height.length - 1;
let best = 0;
while (left < right) {
const width = right - left;
const area = Math.min(height[left], height[right]) * width;
best = Math.max(best, area);
// The shorter line is the bottleneck, so discard it.
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
};GoTested in our runner
func maxArea(height []int) int {
left, right := 0, len(height)-1
best := 0
for left < right {
h := height[left]
if height[right] < h {
h = height[right]
}
area := h * (right - left)
if area > best {
best = area
}
// The shorter line is the bottleneck, so discard it.
if height[left] < height[right] {
left++
} else {
right--
}
}
return best
}C#Tested in our runner
public class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.Length - 1;
int best = 0;
while (left < right) {
int width = right - left;
int area = Math.Min(height[left], height[right]) * width;
best = Math.Max(best, area);
// The shorter line is the bottleneck, so discard it.
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}
}Common mistakes
- Using
max(height[left], height[right])for the water level. Water spills over the shorter wall, so the level is themin. - Moving the taller pointer, as in
if height[left] > height[right]: left += 1. The shorter line caps every container it joins, so keeping it while narrowing the width can only lower the area. Move the shorter side. - Moving both pointers in one iteration. This skips pairs such as a tiny left line with a huge right line, whose partner for a later left may sit at the old right. Move one pointer per step.
- Computing width as
right - left + 1. The lines are points on the x-axis, so the distance between index 1 and index 8 is 7, not 8. Useright - left. - Looping with
while left <= right. When the pointers meet, the pair is one line with itself and has width 0. Useleft < right. - Mixing this up with Trapping Rain Water. Here only two lines form the container and the lines between them are ignored. Do not sum water over the inner bars.
Edge cases
[1,1]: the smallest input. One pair, area 1 * 1 = 1.[0,0,0]: every height is 0, so every area is 0 and the answer is 0.[5,5,5,5]: all heights equal. The widest pair wins with 5 * 3 = 15, and the tie rule keeps the scan correct.[1,2,3,4,5](strictly increasing): the pair (2, 4) gives 3 * 2 = 6, and (1, 4) gives 2 * 3 = 6. The maximum is 6, so check that the scan does not stop early.[10000, 1, 1, ..., 1, 10000]with 10^5 entries: the answer is 10000 * 99999, about 10^9, which still fits in a 32-bit int.- A tall line next to a short one,
[9,1]: the area is min(9,1) * 1 = 1, not 9.
Follow-ups interviewers ask
- Can you prove that moving the shorter pointer never skips the best pair?
- Say
height[left] <= height[right]. Every pair(left, k)withk < righthas width smaller thanright - leftand height at mostheight[left]. Its area is below the area of(left, right), which you already recorded, so droppingleftloses nothing. The mirror case works forright. - What changes if the container may be slanted or the lines have thickness?
- The area formula changes, so the greedy argument has to be checked again. With a fixed thickness per line, width becomes a linear function of index distance and the same elimination argument still holds. With slanted containers the problem is a different geometry problem and the pointer rule no longer applies.
- How is this different from Trapping Rain Water?
- Container With Most Water picks exactly two lines and ignores everything between them. Trapping Rain Water fills water over all bars, so each position holds water up to the lower of the tallest bar on its left and the tallest bar on its right. Both use two pointers and both move the side with the lower wall, but the quantity you add up is different.
Container With Most Water FAQ
What is the time complexity of Container With Most Water?
The two pointer solution runs in O(n) time and O(1) extra space. Each step moves one pointer, and the pointers cover n - 1 positions in total. The brute force version is O(n^2) time and O(1) space.
Why use two pointers for Container With Most Water?
The area depends on width and the shorter height. Starting at maximum width and moving the shorter side is the only move that can raise the height limit. This lets you discard one index per step with a proof that no better pair is lost, which cuts O(n^2) to O(n).
Can Container With Most Water be solved in O(1) extra space?
Yes. The two pointer solution keeps only left, right, and the best area so far. It never builds a map, stack, or sorted copy. The input array is left unmodified.
Do I need to sort the array for Container With Most Water?
No, and sorting would break the problem. The index is the x-coordinate, so reordering the heights changes which lines are next to each other. The pointers work on index order, which is already sorted by position.
What should I do when the two heights are equal?
Move either pointer. With equal heights, both lines are capped by the same value, and each is at its best with the current partner. The usual code moves right in the else branch, and the trace above does the same at step 4.
Why does the answer fit in an int in Java and C#?
The largest possible area is a height of 10^4 times a width of 10^5 minus 1, which is under 10^9. A signed 32-bit int holds up to about 2.1 * 10^9, so no overflow happens.
Asked at
See which companies ask this — Pro
Related problems
- 3Sum · same technique: Converging (Sorted Array Target Sum)
- Two Sum II - Input Array Is Sorted · same technique: Converging (Sorted Array Target Sum)
- 4Sum · same technique: Converging (Sorted Array Target Sum)
- Boats to Save People · same technique: Converging (Sorted Array Target Sum)
- 3Sum Closest · same technique: Converging (Sorted Array Target Sum)
- Trapping Rain Water · next harder, same pattern
- Sort Colors · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers