DSA Tracker

Medium

Container With Most Water

A medium Arrays problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Arrays
Sheets
3
Core for
25 roles
Platform
LeetCode

The problem

Given an integer array of vertical lines, select two lines that together with the horizontal x-axis form a container holding the maximum volume of water.

Example 1

Input
height = [1,8,6,2,5,4,8,3,7]
Output
49
Why
Choosing index 1 (height 8) and index 8 (height 7) yields width 7 and height min(8, 7) = 7, giving area 7 * 7 = 49.

Example 2

Input
height = [1,1]
Output
1
Why
Width is 1 and both heights are 1, giving maximum area 1 * 1 = 1.

Example 3

Input
height = [4,3,2,1,4]
Output
16
Why
The two endpoints at index 0 and 4 both have height 4, producing area 4 * 4 = 16.

Constraints

  • 2 <= height.length <= 10^5
  • 0 <= height[i] <= 10^4

How to think about it

Updated 2026-09-09

Water volume is width multiplied by the shorter of the two boundary heights. Starting at the widest possible separation puts width at its absolute maximum. Moving the taller line inward decreases width without any chance of increasing the bottleneck height; only moving the shorter line inward has any mathematical hope of finding a taller wall to compensate.

Approaches, worst first

  1. Exhaustive pair evaluation

    time O(n^2) · space O(1)

    Examine every pair of lines (i, j) with i < j, calculating (j - i) * min(height[i], height[j]). Guaranteed to find the optimal container, but computes quadratic combinations that are provably inferior to already evaluated wider boundaries.

  2. Inward two-pointer shrinkageWrite this one

    time O(n) · space O(1)

    Place pointers at left = 0 and right = n - 1 while tracking maxArea. At each step, compute the area formed by the boundary pair and advance whichever pointer points to the shorter height. Stops when the pointers meet, inspecting each boundary at most once.

Where people lose marks · 3
  • Advancing both pointers simultaneously when height[left] equals height[right] without checking intermediate containers, which can skip valid solutions.
  • Advancing the pointer with the larger height, which decreases width while guaranteeing the bottleneck cannot improve.
  • Forgetting to update the running maximum area before advancing a boundary pointer.

Full solution

Inward two-pointer shrinkage: width is maximal at the endpoints, and only the shorter wall has any hope of a taller replacement, so it never needs to check a pair twice. O(n) time, O(1) space.

Python
def max_area(height: list[int]) -> int:
    left, right = 0, len(height) - 1
    best = 0
    while left < right:
        width = right - left
        best = max(best, width * min(height[left], height[right]))
        # the shorter wall is the bottleneck, so only moving it can ever help
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return best
JavaScript
function maxArea(height) {
  let left = 0;
  let right = height.length - 1;
  let best = 0;
  while (left < right) {
    const width = right - left;
    best = Math.max(best, width * Math.min(height[left], height[right]));
    if (height[left] < height[right]) left++;
    else right--;
  }
  return best;
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

What each operation costs

OperationTime
look up element by indexO(1)
insert or delete at the startO(n)
search an unsorted collection for a valueO(n)
What usually goes wrong with Arrays
  • Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
  • Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
  • Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.

Which roles need this problem

Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Arrays problems

Problem set and role mapping as of .