Largest Rectangle in Histogram Problem
Description
LeetCode Problem 84.
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 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Example 2:
Input: heights = [2,4]
Output: 4
Constraints:
- 1 <= heights.length <= 10^5
- 0 <= heights[i] <= 10^4
Solution
Approach: Monotonic Stack
The best rectangle is as tall as some bar i and stretches from that bar to the nearest lower bar on each side. Checking every bar by scanning left and right takes O(n2); a stack finds both boundaries for all bars in one pass.
Keep a stack of bar indices whose heights increase from bottom to top. For each new index i with height current:
- While the bar on top of the stack is at least as tall as
current, pop it. Its rectangle cannot reach bari, and the new top of the stack is the nearest lower bar on its left (or there is none, and the rectangle starts at index 0). So the popped bar's rectangle has widthi - left, whereleftis the new top plus one, and areaheight * width. (If barihas the same height, the wider rectangle through both is found later, when bariis popped.) - Push
i.
After the last bar, bars still on the stack have no lower bar to their right. Instead of a second loop, run the loop once more with an imaginary bar of height 0 at index n, which pops all of them.
For [2, 1, 5, 6, 2, 3]: when the bar of height 2 at index 4 arrives, it pops 6 (width 1, area 6) and then 5 (width 4 - 2 = 2, area 10), which is the answer.
The detail to get right is the width: it is measured from the bar below the popped one in the stack, not from the popped bar's own index. Bars between them were popped earlier because they were taller, so the rectangle extends over them too.
Complexity: O(n) time, since each index is pushed and popped once, and O(n) extra space for the stack, where n is the length of heights.
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
n = len(heights)
stack = [] # indices of bars, heights increasing from bottom to top
best = 0
for i in range(n + 1):
# An imaginary bar of height 0 after the end pops every bar left on the stack.
current = heights[i] if i < n else 0
while stack and heights[stack[-1]] >= current:
height = heights[stack.pop()]
# This bar's rectangle spans from just after the new stack top up to i - 1.
left = stack[-1] + 1 if stack else 0
best = max(best, height * (i - left))
stack.append(i)
return best