Largest Rectangle in Histogram — LeetCode 84 Python Solution
HardStackArrayMonotonic Stack
- Problem
- #84
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
Python
stk = []
for i in range(n):
while stk and check(stk[-1], i):
stk.pop()
stk.append(i)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
On study lists
This problem is on NeetCode 150 and Grind 75.
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.