Problem 11

Abstract / Summary

Given two arrays representing heights, find two lines that form a container holding the most water.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0011.cpp

class Solution {
public:
    int maxArea(vector<int>& height) {
        map<int, int> last;
        for (int i = 0; i < height.size(); i++)
            last[height[i]] = i;

        auto maxx = 0;
        vector<int> prune;
        for (int i = 0; i < height.size(); i++)
        {
            int left = height.size() - i;
            int minHeight = maxx / left;

            prune.clear();
            auto l = last.lower_bound(minHeight);
            for (; l != last.end(); l++)
            {
                auto h = l->first;
                auto w = l->second - i;
                if (w <= 0)
                {
                    prune.push_back(h);
                    continue;
                }

                auto area = min(h, height[i]) * w;

                if (maxx < area)
                    maxx = area;
            }

            // prune
            for (auto h : prune)
                last.erase(h);
        }

        return maxx;
    }
};
40 lines | 1007 bytes | submitted August 8, 2023 | GitHub   3% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 61% (9+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the classic “container with most water” problem. It iterates over each possible left boundary, keeps track of the farthest right index for every height value, and computes candidate areas only when they can improve the current best result. By discarding heights that can no longer contribute to a larger area, the algorithm reduces unnecessary work.

Building the Height-to-Index Map

The first phase creates a map that records, for each distinct height, the last (rightmost) index where that height appears. This map enables constant-time lookup of the farthest right position for any height value.

map<int, int> last;
for (int i = 0; i < height.size(); i++)
    last[height[i]] = i;

Because the map stores the most recent index for each height, later lookups always refer to the furthest possible right boundary for that height.

Outer Iteration Over Left Boundaries

The algorithm walks the array from left to right, treating each position i as the left wall of a potential container. For each i it computes the maximum possible width remaining (left) and derives a lower bound on the height (minHeight) that could beat the current maximum area (maxx). This bound allows the inner search to skip heights that are guaranteed to be too small.

auto maxx = 0;
vector<int> prune;
for (int i = 0; i < height.size(); i++)
{
    int left = height.size() - i;
    int minHeight = maxx / left;
    // ...
}

Selecting Candidate Right Walls

Inside the outer loop, the code uses last.lower_bound(minHeight) to start iterating from the smallest height that meets the derived lower bound. For each candidate height h, it computes the width w as the distance from the current left index i to the stored rightmost index for h. If the width is non-positive, the height cannot serve as a right wall for this left position and is marked for removal.

prune.clear();
auto l = last.lower_bound(minHeight);
for (; l != last.end(); l++)
{
    auto h = l->first;
    auto w = l->second - i;
    if (w <= 0)
    {
        prune.push_back(h);
        continue;
    }
    auto area = min(h, height[i]) * w;
    if (maxx < area)
        maxx = area;
}

The min(h, height[i]) expression ensures the container height is limited by the shorter of the two walls, matching the problem definition.

Pruning Unusable Heights

After processing all candidates for a given left index, the algorithm removes any heights that produced a non-positive width. Since those heights are located at indices left of or equal to the current i, they can never serve as a right wall for any later left index, and eliminating them shrinks the map for subsequent iterations.

for (auto h : prune)
    last.erase(h);

Edge Cases Handled

When the computed width w is zero or negative, the code treats the height as irrelevant for the current left position and schedules it for removal. This situation occurs when the rightmost occurrence of a height lies at or before the current left index, meaning no container can be formed with that height as the right wall. By pruning such entries, the algorithm gracefully handles arrays where heights repeat or where the maximum area is formed early in the scan.

The lower-bound calculation (minHeight = maxx / left) also implicitly handles the case where the current best area is zero. In that scenario minHeight becomes zero, causing the inner loop to consider all heights, which is necessary for the first successful area computation.

Performance Optimizations

The use of a map to store the last occurrence of each height provides ordered access, enabling the lower_bound operation to jump directly to the smallest height that could improve the result. This avoids scanning heights that are too short to matter.

Pruning heights whose rightmost index is no longer to the right of the current left pointer reduces the size of the map over time. As the outer loop progresses, the map becomes progressively smaller, leading to fewer iterations in the inner loop and faster lookups.

The calculation of minHeight based on the current maximum area and remaining width creates a dynamic threshold. By raising this threshold as maxx grows, the algorithm discards increasingly larger groups of heights that cannot beat the best area found so far, focusing computational effort on promising candidates only.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a row of tall wooden fences standing in a garden, and each fence has a different height. This program wants to find the biggest rectangular swimming pool that can be built between any two of those fences.

To build a pool, you pick two fences to act as the walls. The water inside the pool needs to stay as high as the shorter of the two walls, because if the water goes any higher, it would spill over the shorter side. The width of the pool is just the distance between those two fences on the ground. To find the secret of the biggest pool, the code keeps track of where the last fence of every height is located.

The code goes on a trip across the fence row, starting from the very first one all the way to the end. For every fence it visits, it tries to see if it can build a bigger pool by pairing the current fence with other fences that exist further down the line. It uses a clever trick to ignore fences that are too short to possibly make a bigger pool than the one already found. If it finds a combination that holds more water, it remembers that new, larger size. It also cleans up its list by getting rid of fences that can no longer help make a bigger pool, which keeps everything moving quickly. By the time it finishes looking at all the fences, it knows exactly how big the largest possible pool can be.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 3 | μ = 3.76 | σ = 1.61

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust JS C Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
linouk23 C++
lkwq007 Python
luangong C++
qiyuangong Java
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
withaarzoo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
luangong C++
qiyuangong Java
ruoru Rust
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
withaarzoo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
62 links | 43 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Container with Most Water - Leetcode 11 - Python'
NeetCode 13 mins
Container with Most Water - Leetcode 11 - Python
YouTube video 'LeetCode #11: Container with most Water | Facebook Interview Question | C++'
Knowledge Center 17 mins
LeetCode #11: Container with most Water | Facebook Interview Question | C++
YouTube video 'LeetCode Container With Most Water Explained - Java'
Nick White 6 mins
LeetCode Container With Most Water Explained - Java
YouTube video 'Container With Maximum Water (LeetCode 11) | Full Solution with Visuals | Study Algorithms'
Nikhil Lohia 13 mins
Container With Maximum Water (LeetCode 11) | Full Solution with Visuals | Study Algorithms
YouTube video 'Container With Most Water | Detailed | With Dry Runs | Leetcode 11 | codestorywithMIK'
codestorywithMIK 19 mins
Container With Most Water | Detailed | With Dry Runs | Leetcode 11 | codestorywithMIK
YouTube video 'Container With Most Water - Leetcode 11 - 2 Pointers (Python)'
Greg Hogg 7 mins
Container With Most Water - Leetcode 11 - 2 Pointers (Python)
YouTube video 'Container With Most Water | Live Coding with Explanation | Leetcode - 11'
Algorithms Made Easy 5 mins
Container With Most Water | Live Coding with Explanation | Leetcode - 11
YouTube video 'Container With Most Water | Arrays & Strings | Leetcode 11 solution in Hindi | gfg Solution in Hindi'
Pepcoding 24 mins
Container With Most Water | Arrays & Strings | Leetcode 11 solution in Hindi | gfg Solution in Hindi
YouTube video '11. Container With Most Water || LEETCODE || code + intuition'
Code with Alisha 9 mins
11. Container With Most Water || LEETCODE || code + intuition
YouTube video 'Container With Most Water | Leetcode 11 | Two pointers | Day-5'
Ayushi Sharma 22 mins
Container With Most Water | Leetcode 11 | Two pointers | Day-5
YouTube video 'DSA Phir se with Sumeet | Leetcode 11 | Container with most water'
Pepcoding 16 mins
DSA Phir se with Sumeet | Leetcode 11 | Container with most water
YouTube video 'Container With Most Water - LeetCode 11 - Python'
Deepti Talesra 9 mins
Container With Most Water - LeetCode 11 - Python
YouTube video '[Java] Leetcode 11. Container With Most Water [Two Pointers #5]'
Eric Programming 9 mins
[Java] Leetcode 11. Container With Most Water [Two Pointers #5]
YouTube video 'Container With Most Water - LeetCode 11 - JavaScript'
AlgoJS 6 mins
Container With Most Water - LeetCode 11 - JavaScript
YouTube video 'Container With Most Water | Detailed Explanation | LeetCode Solution | Geekific'
Geekific 4 mins
Container With Most Water | Detailed Explanation | LeetCode Solution | Geekific
YouTube video 'Container With Most Water - LeetCode 11 - Coding Interview Questions'
One Code Man 4 mins
Container With Most Water - LeetCode 11 - Coding Interview Questions
YouTube video 'CONTAINER WITH MOST WATER | LEETCODE # 11 | PYTHON 2 POINTERS SOLUTION'
Cracking FAANG 12 mins
CONTAINER WITH MOST WATER | LEETCODE # 11 | PYTHON 2 POINTERS SOLUTION
YouTube video 'Container With Most Water | LeetCode 11 |  Two Pointer'
Naresh Gupta 9 mins
Container With Most Water | LeetCode 11 | Two Pointer
YouTube video 'Container With Most Water - LeetCode 11 - Java'
LeetCode University 16 mins
Container With Most Water - LeetCode 11 - Java
YouTube video 'Container With Most Water Python Solution - LeetCode #11'
Professor Oakes 5 mins
Container With Most Water Python Solution - LeetCode #11
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality