Menu
CoddyTech

Largest Rectangle in Histogram

A histogram is a row of bars standing side by side with no gaps, each one unit wide: heights[i] is the height of bar i. A rectangle inside it covers a run of neighbouring bars and can be no taller than the shortest bar in that run.

Return the largest area such a rectangle can have.

Function

largestRectangleArea(heights: integer-array) → integer
heightsinteger-array
the height of each bar, from left to right
Returnsinteger
the area of the largest rectangle that fits in the histogram

Constraints

  • 1 ≤ heights.length ≤ 2 × 104
  • 0 ≤ heights[i] ≤ 105
  • Every bar is one unit wide, so a rectangle over bars i to j is j-i+1 units wide.

Examples

Input
heights = [2, 5, 6, 3, 4, 1]
Output
12
Explanation
The four bars 5, 6, 3 and 4 are all at least 3 tall, so a rectangle of height 3 spans them: 3 × 4 = 12. The two tallest bars, 5 and 6, only give 5 × 2 = 10.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

Suppose each bar has its own width, given in a second array. What changes in the one-pass stack solution?

Reset code
def largestRectangleArea(heights):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

heights = [2, 5, 6, 3, 4, 1]

Expected

12