#84HardMonotonic Stack

Largest Rectangle in Histogram

Monotonic stack finds each bar's left/right boundary in O(n).

AmazonGoogleMicrosoftDeutsche Bank

Problem Statement

Given an array of integers heights representing the histogram's bar heights where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Examples

Example 1

Input:heights = [2,1,5,6,2,3]
Output:10

Explanation: The rectangle spans bars 2-3 (heights 5 and 6), area = 5×2 = 10.

Example 2

Input:heights = [2,4]
Output:4

Constraints

  • 1 ≤ heights.length ≤ 10⁵
  • 0 ≤ heights[i] ≤ 10⁴

Solutions

1
Brute Force — Try all bar pairs
TimeO(n²)SpaceO(1)

For each pair (i, j), the rectangle height is min(heights[i..j]) and width is j-i+1. O(n²) or O(n³).

Visual Animation
def largestRectangleArea(heights: list[int]) -> int:
    best = 0
    for i in range(len(heights)):
        min_h = heights[i]
        for j in range(i, len(heights)):
            min_h = min(min_h, heights[j])
            best = max(best, min_h * (j - i + 1))
    return best

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Monotonic Stack to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems