InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Largest Rectangle in Histogram

hard Original ↗ 00:00

Problem

You are given an array heights where heights[i] is the height of the i-th bar of a histogram; every bar has width 1 and stands on a common baseline. Return the area of the largest axis-aligned rectangle that fits entirely inside the histogram.

Equivalently: choose a contiguous range of bars [l, r]; the rectangle over that range has area (r - l + 1) * min(heights[l..r]). Maximize that product.

Examples

Example 1

Input: heights = [2, 1, 5, 6, 2, 3] Output: 10 Explanation: bars 5 and 6 (indices 2–3) support a rectangle of height 5 and width 2 → area 10.

Example 2

Input: heights = [2, 4] Output: 4 Explanation: best is the single bar of height 4 (area 4); using both bars gives only 2 × 2 = 4 as well.

Example 3

Input: heights = [3, 3, 3] Output: 9 Explanation: the whole histogram is a 3 × 3 rectangle.

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4
  • With n = 10^5, the O(n²) all-pairs scan is too slow — an O(n) or O(n log n) solution is expected.

Think about it first

Hint 1 Fix one bar and ask: what is the largest rectangle whose *height equals this bar's height*? Every maximal rectangle is of that form for whichever bar is its shortest.
Hint 2 For bar `i`, that rectangle extends left to the nearest bar strictly shorter than `heights[i]`, and right likewise. So the whole problem reduces to finding each bar's *previous smaller* and *next smaller* element.
Hint 3 Sweep once with a stack of indices whose heights are non-decreasing. When the current bar is shorter than the stack top, the popped bar has found its right boundary (the current index) and its left boundary (the new stack top) — compute its area right there.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug