Largest Rectangle in Histogram - 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.
A rectangle in a histogram is formed by selecting a contiguous range of bars. The height of the rectangle is determined by the shortest bar in that range, and the width is the number of bars in the range.
Your goal is to find the maximum possible area among all such rectangles.
Input & Output
Example 1 — Standard Histogram
$
Input:
heights = [2,1,5,6,2,3]
›
Output:
10
💡 Note:
The largest rectangle has height 5 and width 2 (indices 2-3), giving area = 5 × 2 = 10
Example 2 — Single Bar
$
Input:
heights = [2,4]
›
Output:
4
💡 Note:
The largest rectangle is the single bar with height 4 and width 1, area = 4 × 1 = 4
Example 3 — Decreasing Heights
$
Input:
heights = [6,5,4,3,2,1]
›
Output:
12
💡 Note:
Best rectangle uses height 3 spanning 4 bars (indices 0-3), area = 3 × 4 = 12
Constraints
- 1 ≤ heights.length ≤ 105
- 0 ≤ heights[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Histogram
Array of heights: [2,1,5,6,2,3]
2
Find Rectangles
Each bar can be minimum height of some rectangle
3
Maximum Area
Largest rectangle has area 10 (height=5, width=2)
Key Takeaway
🎯 Key Insight: Each bar can be the minimum height of some rectangle - use a monotonic stack to efficiently find the boundaries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code