Problem 84

Abstract / Summary

Given a list of bar heights, find the largest rectangle that can be formed inside the histogram.

Note

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

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;
    }
};
32 lines | 862 bytes | submitted August 27, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 51% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Monotonic Stack
  • Stack
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 4.78 | σ = 1.57

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 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++
53 links | 38 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LARGEST RECTANGLE IN HISTOGRAM - Leetcode 84 - Python'
NeetCode 18 mins
LARGEST RECTANGLE IN HISTOGRAM - Leetcode 84 - Python
YouTube video 'Largest Rectangle in Histogram - Leetcode 84 | One-Pass Monotonic Stack | Java & Python'
Code With K5KC 9 mins
Largest Rectangle in Histogram - Leetcode 84 | One-Pass Monotonic Stack | Java & Python
YouTube video 'Largest Rectangle in Histogram - Leetcode 84 - Stacks (Python)'
Greg Hogg 11 mins
Largest Rectangle in Histogram - Leetcode 84 - Stacks (Python)
YouTube video 'Largest Rectangle in Histogram | Leetcode 84'
Pepcoding 35 mins
Largest Rectangle in Histogram | Leetcode 84
YouTube video 'Largest Rectangle in Histogram | Live Coding with Explanation | Leetcode - 84'
Algorithms Made Easy 13 mins
Largest Rectangle in Histogram | Live Coding with Explanation | Leetcode - 84
YouTube video 'LeetCode 84. Largest Rectangle in Histogram 中文解释 Chinese Version'
happygirlzt 16 mins
LeetCode 84. Largest Rectangle in Histogram 中文解释 Chinese Version
YouTube video 'Largest Rectangle in Histogram | Live Coding with Explanation | Leetcode - 84'
Algorithms Made Easy 21 mins
Largest Rectangle in Histogram | Live Coding with Explanation | Leetcode - 84
YouTube video 'LeetCode 84. Largest Rectangle in Histogram Explanation and Solution'
happygirlzt 17 mins
LeetCode 84. Largest Rectangle in Histogram Explanation and Solution
YouTube video 'Largest Rectangle in Histogram |  LeetCode 84 | C++, Java, Python'
Knowledge Center 23 mins
Largest Rectangle in Histogram | LeetCode 84 | C++, Java, Python
YouTube video 'Largest Rectangle in Histogram | LeetCode 84 | Theory + Python code'
Sai Anish Malla 22 mins
Largest Rectangle in Histogram | LeetCode 84 | Theory + Python code
YouTube video 'Largest Rectangle in Histogram | Leeetcode 84  | Live coding session  🔥🔥🔥 | Monotonic Stacks O(n)'
Coding Decoded 15 mins
Largest Rectangle in Histogram | Leeetcode 84 | Live coding session 🔥🔥🔥 | Monotonic Stacks O(n)
YouTube video 'Leetcode 84. Largest Rectangle in Histogram | Monotonic Stack (Optimal O(n)) | Python Solution'
StatLearn Tech 26 mins
Leetcode 84. Largest Rectangle in Histogram | Monotonic Stack (Optimal O(n)) | Python Solution
YouTube video 'Largest Rectangle in Histogram | largest rectangle in histogram | leetcode 84'
Naresh Gupta 16 mins
Largest Rectangle in Histogram | largest rectangle in histogram | leetcode 84
YouTube video '84. Largest Rectangle in Histogram || NEETCODE 150'
TechWithSaumya 35 mins
84. Largest Rectangle in Histogram || NEETCODE 150
YouTube video 'Daily Leetcode #669: Jan 29, 2022 - 84. Largest Rectangle in Histogram'
Programming Live with Larry 32 mins
Daily Leetcode #669: Jan 29, 2022 - 84. Largest Rectangle in Histogram
YouTube video 'Leetcode 84: Largest Rectangle in Histogram in Telugu | Bruteforce, Stack | Python DSA | srkcodes'
Srk Codes 17 mins
Leetcode 84: Largest Rectangle in Histogram in Telugu | Bruteforce, Stack | Python DSA | srkcodes
YouTube video 'LeetCode 84. Largest Rectangle in Histogram'
Happy Coding 14 mins
LeetCode 84. Largest Rectangle in Histogram
YouTube video 'LeetCode 84: Largest Rectangle in Histogram | C# Solution | Stack Approach |'
Code Scribbler 20 mins
LeetCode 84: Largest Rectangle in Histogram | C# Solution | Stack Approach |
YouTube video 'Leetcode Question 84 "Largest Rectangle in Histogram" in Javascript'
Ghumman Tech 10 mins
Leetcode Question 84 "Largest Rectangle in Histogram" in Javascript
YouTube video 'Daily Leetcode #275: Dec 31, 2020 - 84. Largest Rectangle in Histogram'
Programming Live with Larry 28 mins
Daily Leetcode #275: Dec 31, 2020 - 84. Largest Rectangle in Histogram
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

2 hard
3 solutions   August 27, 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