HardArrayStackMonotonic Stack

Largest Rectangle in Histogram

LeetCode
1 approach, code in all languages

You are given an array `heights` where each entry is the height of a bar in a histogram and every bar has width `1`.

Consider any rectangle whose top edge is flat and that fits entirely under the histogram outline, spanning one or more contiguous bars. The height of such a rectangle is limited by the shortest bar it covers, and its width is the number of consecutive bars it spans.

Return the area of the largest rectangle that can be formed within the histogram.

Example 1

Input: heights = [2,1,5,6,2,3]

Output: 10

The bars of height 5 and 6 form a rectangle of height 5 and width 2, giving area 10, which is the maximum.

Example 2

Input: heights = [2,4]

Output: 4

The single bar of height 4 gives area 4, beating the width-2 rectangle of height 2 (area 4 as well but not larger).

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now