HardNo. 0084

Largest Rectangle in Histogram — LeetCode 84 Python Solution

Pattern
Stack
Topics
Stack, Array, Monotonic Stack
On study lists
NeetCode 150 and Grind 75
Reading time
2 min

The problem

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Example

Input
heights = [2,1,5,6,2,3]
Output
10
Explanation
The above is a histogram where width of each bar is 1.

Python solution

PythonSolution
stk = []
for i in range(n):
    while stk and check(stk[-1], i):
        stk.pop()
    stk.append(i)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 84. Largest Rectangle in Histogram is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0456132 PatternMedium
0503Next Greater Element IIMedium
0654Maximum Binary TreeMedium
0739Daily TemperaturesMedium
0853Car FleetMedium
1008Construct Binary Search Tree from Preorder TraversalMedium

Frequently asked questions

How hard is LeetCode 84. Largest Rectangle in Histogram?

LeetCode 84. Largest Rectangle in Histogram is rated Hard on LeetCode.

What is the time complexity of LeetCode 84. Largest Rectangle in Histogram?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 84. Largest Rectangle in Histogram?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 84. Largest Rectangle in Histogram cover?

LeetCode 84. Largest Rectangle in Histogram is tagged Stack, Array and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.