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 Histogram INPUT 2 1 5 6 2 3 heights array: 2 1 5 6 2 3 0 1 2 3 4 5 ALGORITHM STEPS 1 Use Stack Store indices of bars in increasing height 2 Pop when smaller Current bar shorter than stack top: pop and calc 3 Calculate Area height x width where width = right - left - 1 4 Track Maximum Update max area after each pop Stack (indices): [0, 2, 3] monotonic increasing FINAL RESULT width=2 h=5 Largest Rectangle: Area = 5 x 2 = 10 (bars at index 2,3) Output: 10 Key Insight: Use a monotonic stack to efficiently find the boundaries of rectangles. When we encounter a bar shorter than the stack top, we know the right boundary. The left boundary is the previous stack element. Time Complexity: O(n) - each bar pushed/popped once. Space Complexity: O(n) for the stack. TutorialsPoint - Largest Rectangle in Histogram | Optimal Solution (Monotonic Stack)
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