sagelearnai

Largest Rectangle in Histogram

Difficulty: Hard · Pattern: Stack & Monotonic Stack · LeetCode #84

heights[i] is the height of bar i in a histogram where every bar has width 1. Return the area of the largest rectangle that fits entirely within the histogram.

Examples

text
heights = [2, 1, 5, 6, 2, 3]  →  10    (bars 5 and 6: height 5 × width 2)
heights = [2, 4]              →  4
heights = [3, 3, 3]           →  9

Hints

  1. For each bar, the best rectangle using its full height extends left and right until a shorter bar.
  2. You need the previous-smaller and next-smaller index for every bar.
  3. An increasing stack gives both: when a bar is popped, the current index is its next-smaller, and the new top is its previous-smaller.

Approach

Maintain a stack of indices with increasing heights. When heights[i] is lower than the top's height, pop the top j: its rectangle spans from just after the new stack top to i − 1, so width = i − stack[-1] − 1 (or i if the stack is empty). Area = heights[j] × width. A sentinel height 0 at the end flushes the stack. Each bar is pushed and popped once.

Complexity

Time: O(n). Space: O(n).

Python solution
def largestRectangleArea(heights):
    st, best = [], 0
    for i, h in enumerate(heights + [0]):        # sentinel flushes the stack
        while st and heights[st[-1]] > h:
            j = st.pop()
            left = st[-1] if st else -1
            best = max(best, heights[j] * (i - left - 1))
        st.append(i)
    return best
JavaScript solution
function largestRectangleArea(heights) {
  const st = []; let best = 0;
  for (let i = 0; i <= heights.length; i++) {
    const h = i === heights.length ? 0 : heights[i];
    while (st.length && heights[st[st.length - 1]] > h) {
      const j = st.pop();
      const left = st.length ? st[st.length - 1] : -1;
      best = Math.max(best, heights[j] * (i - left - 1));
    }
    st.push(i);
  }
  return best;
}