DSA AnimatorREVISION VIDEOS
← Back to problems
New

Container With Most Water — LeetCode 11 video explanation

Each number is the height of a vertical line. Pick two lines that, together with the x axis, hold the most water. The water is the shorter line times the distance between them.

Loading videos…

DSA Animator › DSA Revision › Arrays › Container With Most Water

Key moments in the Container With Most Water video

0:03Problem0:14Example0:26Brute force0:32Key idea0:45Dry run1:08Code1:22Takeaway

What you will learn

Remember: start widest, and always move the shorter line. The shorter line limits the water. The video solves Container With Most Water (LeetCode 11, Medium) with the Two Pointers pattern from the Arrays topic, and you can replay every step in the interactive Container With Most Water animation.

Container With Most Water video transcript

Problem

Each number is the height of a vertical line. Pick two lines that, together with the x axis, hold the most water. The water is the shorter line times the distance between them.

Example

For 1, 8, 6, 2, 5, 4, 8, 3, 7, the best pair is the lines at index 1 and index 8. The shorter is 7, the width is 7, so the area is 49.

Brute force

Checking every pair is O of n squared. And picking the two tallest lines fails, because the width matters too.

Key idea

Start with the widest container, one pointer at each end. The water level is set by the shorter line, so moving the taller line inward can never help. So always move the shorter line inward, and keep the best area.

Dry run

The ends are heights 1 and 7, width 8, so the area is 8. Height 1 is shorter, so the left pointer moves to height 8. Now 8 and 7, width 7, give 49, the new best. 7 is now shorter, so the right pointer moves left. The next areas are 18, then 40, then smaller ones, none better than 49. When the pointers meet, the answer is 49.

Code

In code, start left at 0 and right at the end. Compute the area as the shorter height times the width, and keep the best. Move whichever pointer has the shorter line. Each step moves one pointer, so it's O of n time and O of 1 space.

Takeaway

Remember: start widest, and always move the shorter line. The shorter line limits the water.

More Arrays revision videos

← All 185 DSA revision videos