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
Largest Rectangle in HistogramInput: [2,1,5,6,2,3]215623Largest RectangleHeight = 5, Width = 2Algorithm Steps:1. For each bar, find maximum rectangle2. where that bar is the shortest3. Use stack to track boundaries efficiently4. Best area: 5 × 2 = 10Output: 10
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
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
67.9K Views
High Frequency
~25 min Avg. Time
2.8K 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