SDE & MLE Prep

84. Largest Rectangle in Histogram

Problem

heights are the bar heights of a histogram with bars of width 1. Return the area of the largest rectangle that fits entirely inside the histogram.

Example: [2,1,5,6,2,3] → 10 (height 5 across the bars 5 and 6)

Constraints: n ≤ 10⁵.

Increasing stack of indices. When bar i is lower than the top, the top bar's rectangle is bounded: right edge i, left edge = new top after popping. Append a sentinel 0 to flush the stack.

heights 2 1 5 6 2 3
at i=4 (h=2): pop 6 -> width 1 -> 6
              pop 5 -> width 2 (idx 2..3) -> 10   <- max

Complexity: O(n).

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        st, best = [], 0              # increasing stack of indices
        for i, h in enumerate(heights + [0]):
            while st and heights[st[-1]] >= h:
                top = heights[st.pop()]
                left = st[-1] if st else -1
                best = max(best, top * (i - left - 1))
            st.append(i)
        return best