Skip to content
Preptima
hardCodingConceptMidSenior

Find the largest rectangle in a histogram in linear time, and tell me what the stack holds at every step.

Keep a stack of bar indices with strictly increasing heights. When a bar no taller than the top arrives, pop: the popped bar's rectangle runs from just after the new top to just before the current bar. A height-zero sentinel flushes the stack. Each index is pushed once and popped at most once, so it is O(n).

5 min readUpdated 2026-10-09Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Use a monotonic stack of bar indices whose heights strictly increase from bottom to top. When a bar arrives that is no taller than the top, pop the top. Its rectangle runs from just after the new top to just before the arriving bar. A sentinel bar of height zero at the end flushes whatever is left. Every index is pushed once and popped at most once, so the largest rectangle takes O(n) time and O(n) space.

Was this answer helpful?

Likely follow-ups

  • Find the largest rectangle of 1s in a binary matrix. How does the histogram scan become the inner loop?
  • Write the two-pass version with previous-smaller and next-smaller arrays. What does it make easier to explain?
  • Return the boundaries of the best rectangle, not just its area. What extra state do you keep on pop?
  • Why does splitting the histogram at its minimum bar degrade to quadratic time on sorted input?

Related questions