InterviewPrepKit

Home / Coding / Stack

Largest Rectangle in Histogram

hard Original β†—
Solving tips
  • Reframe as: for each bar, find the largest rectangle whose height equals that bar, bounded by the previous-smaller and next-smaller bars on each side.
  • Sweep once with a monotonic increasing stack of indices; when the current bar is shorter than the top, the popped bar has found its right boundary (current i) and left boundary (new top).
  • Compute the popped bar's width as i - stack_top_after_pop - 1 (using -1 when the stack empties), not i - popped_index, since it may extend left over shorter-popped bars.
  • Append a sentinel bar of height 0 to flush the stack at the end; target O(n) time and O(n) space.

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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.