Largest Rectangle in a Skyline
Difficulty: Hard · Pattern: Monotonic Stack · Concept: General Coding (DSA) — Core Patterns to Drill
Given a list of non-negative integers representing bar heights in a histogram (each bar has width 1, standing side by side), find the area of the largest rectangle that can be formed using contiguous bars, where the rectangle's height is limited by the shortest bar it spans.
The brute force checks every pair of left/right bounds and finds the minimum height in between — or worse. The trick: for every bar, its own height only matters if you can figure out, cheaply, how far it can extend left and right before hitting something shorter. A monotonic stack (indices kept in increasing-height order) computes exactly that in one pass.
Your task: implement largest_rectangle_area(heights) in time. Return 0 for an empty list.
Next: Daily Temperatures (another monotonic-stack problem), or continue to Design a Min Stack