Workspace Container With Most Water
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Container With Most Water visualizer

Two vertical walls enclose width times the shorter height. Return the greatest area among all pairs.

EXECUTION LAB

Two vertical walls enclose width times the shorter height. Return the greatest area among all pairs.

Input and constraints
  • Each value must be nonnegative.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
left = 0
right = (len(values) - 1)
best = 0
while (left < right):
area = (min(values[left], values[right]) * (right - left))
best = max(area, best)
if (values[left] <= values[right]):
left = (left + 1)
else:
right = (right - 1)
return best

Visualizer

Step 1 of 5
02left
18
23
36
45right

Inspect the current state

Compare this container area 8 with the current best.

Variable watch

left 0right 4area 8best 0

Step explanation

Compare this container area 8 with the current best.

comparisons 1reads 2writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

Worked explanation

A reservoir spills over the lower of its two retaining walls.

Guided solution

Moving the taller wall cannot improve the area while the shorter wall is fixed.

O(n) time · O(1) auxiliary space

Examples

Worked example · {"values":[2,8,3,6,5],"target":0} ⇒ 15

Edge case 1 · {"values":[],"target":0} ⇒ 0

Edge case 2 · {"values":[4],"target":0} ⇒ 0

Progressive hints

Hint 1A reservoir spills over the lower of its two retaining walls.
Hint 2Moving the taller wall cannot improve the area while the shorter wall is fixed.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Height alone ignores the distance between walls.

Interview follow-up

Does the choice matter when both walls have equal height?

Continue learning

Practice related DSA questions in the same topic.