DSA problem
Largest Rectangle in Histogram
Given an array heights of non-negative integers representing the heights of bars in a histogram where the width of each bar is 1, find the area of the largest rectangle that fits entirely within the histogram.
A rectangle of height h can extend horizontally over any contiguous range of bars whose heights are all at least h. To find the largest such rectangle, for each bar i consider the rectangle whose height equals heights[i]: its left boundary is the index after the previous bar shorter than heights[i] (or 0 if none), and its right boundary is the index before the next bar shorter than heights[i] (or n - 1 if none). Its area is heights[i] * (right - left + 1).
Computing the previous-less and next-less indices for every bar can be done in O(n) using a monotonic increasing stack of indices. As we scan left-to-right, whenever the current bar is shorter than the bar at the stack's top, the top has found its "next less" — pop and compute the area. A standard implementation pushes a sentinel height 0 at the end of the array so the final stack is fully flushed by the iteration.
After flushing, the answer is the maximum area found. The total work is O(n) time and O(n) space for the stack.
Examples
heights = [2,1,5,6,2,3]10heights = [2,4]4heights = [6,7,5,2,4,5,9,3]16Constraints
- 1 <= heights.length <= 10^5
- 0 <= heights[i] <= 10^4
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.