Problem · Array
Largest Rectangle in Histogram
Learn this problemProblem statement
Given an array heights of non-negative bar heights, where every bar has width 1, return the area of the largest rectangle that can be formed using one or more consecutive bars.
Interview follow-up
The interviewer asked for a brute-force approach, why it is inefficient, the optimal monotonic-stack solution, time and space analysis, and a clean implementation. They emphasized understanding the reasoning rather than only reaching the final answer.
Function
largestRectangleArea(heights: int[]) → intExamples
Example 1
heights = [2,1,5,6,2,3]return = 10The bars of heights 5 and 6 form a rectangle of height 5 and width 2.
Example 2
heights = [2,4]return = 4