C++ 0084.cpp
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
map<int, int> start;
heights.push_back(0);
int best = 0;
for (int i = 0; i < heights.size(); i++)
{
auto h = heights[i];
auto left = i;
auto higher = start.upper_bound(h);
for (auto reduce = higher; reduce != start.end(); reduce++)
{
int area = reduce->first * (i - reduce->second);
best = max(best, area);
left = min(left, reduce->second);
}
if (higher != start.end() && higher->first == h)
higher++;
start.erase(higher, start.end());
if (start.count(h) == 0)
start[h] = left;
}
return best;
}
};
Difficulty
and has an acceptance rate of about 51% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Monotonic Stack
- Stack
AI Disclaimer
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.
Code Walkthrough
Overview
The presented implementation solves the classic “largest rectangle in a histogram” problem. It iterates through the bar heights while maintaining a map that records, for each distinct height, the leftmost index where that height (or a taller one) begins a potential rectangle. By inserting a sentinel height of zero at the end, the algorithm guarantees that all pending rectangles are evaluated. The map is kept in ascending order of heights, which enables efficient identification of heights that are higher than the current bar and the removal of those that can no longer contribute to larger areas.
Core Data Structure
map<int, int> start;
The start map stores pairs of (height, leftmost_index). Because std::map is ordered by key, the keys are sorted heights. This ordering is crucial for the subsequent lookup of the first height greater than the current one.
Main Loop
heights.push_back(0);
int best = 0;
for (int i = 0; i < heights.size(); i++)
{
auto h = heights[i];
auto left = i;
// ...
}
A sentinel value 0 is appended to force the processing of any remaining bars. The loop variable i traverses each position, extracting the current height h and initializing left to the current index. best accumulates the maximum rectangle area found so far.
Identifying Higher Bars
auto higher = start.upper_bound(h);
for (auto reduce = higher; reduce != start.end(); reduce++)
{
int area = reduce->first * (i - reduce->second);
best = max(best, area);
left = min(left, reduce->second);
}
upper_bound returns an iterator to the first entry whose height exceeds h. The subsequent for loop iterates over all such higher entries. For each higher height, the potential rectangle width is the distance from its stored leftmost index to the current position i. The area is computed as height * width and compared with best. The left variable is updated to the smallest leftmost index among the processed entries, ensuring that when the current height is inserted, it reflects the furthest possible extension to the left.
Cleaning Up the Map
if (higher != start.end() && higher->first == h)
higher++;
start.erase(higher, start.end());
If an entry with exactly the same height as h exists, the iterator is advanced past it so that the erase operation removes only entries with strictly greater heights. This step discards heights that can no longer produce larger rectangles because a shorter or equal bar has been encountered, effectively keeping the map minimal.
Inserting the Current Height
if (start.count(h) == 0)
start[h] = left;
When the current height is not already present in the map, it is inserted with the computed left index. This insertion records the earliest position from which a rectangle of height h can start, taking into account any earlier taller bars that have been merged into the current left boundary.
Edge Cases Handled
The algorithm gracefully handles an empty input vector because the sentinel 0 ensures the loop runs at least once, and best remains 0. A single bar is processed similarly; the sentinel forces the evaluation of the rectangle formed by that bar. Repeated heights are managed by the if (start.count(h) == 0) guard, which prevents duplicate keys and ensures that the leftmost index for a given height is preserved. The presence of decreasing sequences of heights triggers the for loop over higher entries, guaranteeing that each taller bar’s rectangle is evaluated before it is removed from the map.
Performance Optimizations
The choice of an ordered map provides logarithmic time for insertion, lookup, and erasure, while also enabling range-based erasure of all entries with heights greater than the current one in a single operation. By erasing a contiguous suffix of the map (start.erase(higher, start.end())), the implementation avoids repeated deletions of individual elements, reducing overhead. The use of upper_bound to locate the first higher height eliminates the need to scan the entire map, focusing work only on relevant entries. The sentinel 0 eliminates a separate final pass to flush remaining entries, consolidating all work within the main loop.
Flow Summary
The algorithm proceeds by extending the current rectangle to the right as long as heights are non-decreasing. When a lower height appears, it retrospectively computes areas for all taller heights that terminate at the current index, updates the global maximum, and prunes those heights from the map. The leftmost index is continuously adjusted to reflect the earliest start point for the current height, ensuring that future rectangles can span the maximum possible width. The final return value best holds the largest rectangle area discovered throughout the scan.
ELI5 - Simplified Explanation
Imagine you have a long row of colorful building blocks standing up, and each one has a different height. You want to see which rectangle you can fit perfectly underneath them.
The code looks at all these blocks one at a time, moving from the left side to the right side. It uses a special list to keep track of the different heights seen so far and where those sections started. Think of this list like a notebook where the labels show how tall a section is and the numbers show the spot where that height first began.
As the code walks along the row, it checks if the current block is shorter than the ones it has already seen. If the new block is shorter, it knows that the taller blocks cannot continue anymore. The code stops to calculate how big the rectangle could be using those taller blocks that are now ending. It compares that size to the biggest one found so far to make sure the best one is always remembered.
After checking those taller blocks, it cleans up the list by removing the ones that are now too tall to keep going. It then writes down the height of the new block and the earliest spot it could extend back to. By the time it reaches the very end of the row, it has checked every possible rectangle shape and knows which one covers the most space.
Code Quality
Complexity Analysis
Other Solutions
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 | C# | Rust | Java | Go | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Rust | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| wisdompeak | Python | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Rust | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| wisdompeak | Python | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 85: Maximal Rectangle
- problem 1793: Maximum Score of a Good Subarray
- problem 2282: Number of People That Can Be Seen in a Grid
- problem 2345: Finding the Number of Visible Mountains
- problem 2863: Maximum Length of Semi-Decreasing Subarrays
Solved On The Same Day
- problem 42: Trapping Rain Water
- problem 403: Frog Jump
Extra
- 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