Problem · Array

Largest Rectangle in Histogram

Learn this problem
HardShipsyONSITE INTERVIEW

Problem 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[]) → int

Examples

Example 1

heights = [2,1,5,6,2,3]return = 10

The bars of heights 5 and 6 form a rectangle of height 5 and width 2.

Example 2

heights = [2,4]return = 4
drafts saved locally
public int largestRectangleArea(int[] heights) {
  // write your code here
}
heights[2,1,5,6,2,3]
expected10
checking account