Typorithm · medium

Container With Most Water

container-with-most-watertwo-pointersconverginggreedy-movearea
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Container With Most Water

0%

Two Pointers

Width starts maximal; move whichever wall is shorter inward, since only a taller wall can ever beat the current area.

The water held by two walls is the shorter height times the distance between them.

Start with the widest container and shrink width by moving a pointer inward.

Always move the shorter wall — keeping it could never increase area, while a new taller wall might.

01

Area = min(height) x width.

02

Start at maximum width.

03

Move the shorter wall inward.

function maxArea(height) {
  let left = 0;
  let right = height.length - 1;
  let best = 0;

  while (left < right) {
    const area = Math.min(height[left], height[right]) * (right - left);
    best = Math.max(best, area);
    if (height[left] < height[right]) {
      left += 1;
    } else {
      right -= 1;
    }
  }

  return best;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Area = shorter x width

Water is bounded by the shorter wall times the distance.

const area = Math.min(height[left], height[right]) * (right - left)

2. Track maximum

Keep the largest area seen.

best = Math.max(best, area)

3. Drop the shorter

Moving the taller wall can only shrink width and area, so move the shorter.

if (height[left] < height[right]) {
      left += 1;
    }

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Container With Most Water: Lesson & Practice · Typorithm | ApplyDjinn