Largest Rectangle in Histogram - Problem

Imagine you're looking at a histogram - a bar chart where each bar has a height and width of 1 unit. Your task is to find the largest rectangle that can be formed within this histogram.

Given an array heights where heights[i] represents the height of the i-th bar, you need to calculate the maximum area of any rectangle that can be formed using one or more consecutive bars.

The key insight is that a rectangle's height is limited by the shortest bar it contains, but it can extend horizontally as far as possible while maintaining that minimum height.

Example: For heights [2,1,5,6,2,3], the largest rectangle has area 10 (height=5, width=2, using bars at indices 2 and 3).

Input & Output

example_1.py โ€” Basic Case
$ Input: [2,1,5,6,2,3]
โ€บ Output: 10
๐Ÿ’ก Note: The largest rectangle has area 10, formed by bars with heights [5,6] (indices 2-3). The rectangle has height 5 (minimum of the two bars) and width 2, giving area 5ร—2=10.
example_2.py โ€” Single Bar
$ Input: [2,4]
โ€บ Output: 4
๐Ÿ’ก Note: We can choose either a rectangle of height 2 and width 2 (area=4) or height 4 and width 1 (area=4). Both give the same maximum area of 4.
example_3.py โ€” Edge Case
$ Input: [1]
โ€บ Output: 1
๐Ÿ’ก Note: With only one bar of height 1, the largest (and only) rectangle has area 1ร—1=1.

Visualization

Tap to expand
BILLBOARDArea = 10Largest Rectangle in HistogramFind the largest billboard that fits within the city skyline
Understanding the Visualization
1
Survey the Skyline
Look at all buildings and identify potential billboard positions
2
Track Promising Buildings
Keep a list of buildings where billboards could start, in height order
3
Hit a Shorter Building
When you reach a shorter building, calculate rectangles ending there
4
Find Maximum Area
The billboard with the largest area is your answer
Key Takeaway
๐ŸŽฏ Key Insight: Use a monotonic stack to efficiently track potential rectangle starting positions. When heights decrease, we can immediately calculate all rectangles ending at that point!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each bar is pushed and popped from stack at most once, giving us linear time

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Stack can contain up to n elements in worst case (strictly increasing heights)

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค heights.length โ‰ค 105
  • 0 โ‰ค heights[i] โ‰ค 104
  • All heights are non-negative integers
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
67.0K Views
High Frequency
~25 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen