NeetCode #378LC-84HardStackNC 150NC 250
← Back to All Problems#378 · #84 · Largest Rectangle in Histogram(柱状图中最大的矩形)
📌 Problem Statement & Constraints
Given an array
heights representing the heights of bars of width 1 in a histogram, return the area of the largest rectangle that fits inside the histogram. Constraints: 1 <= heights.length <= 10^5, 0 <= heights[i] <= 10^4.💡 Core Algorithmic Approaches
- For each bar, the largest rectangle using that bar as the limiting height extends left and right until a shorter bar is found.
- A monotonically increasing stack of indices identifies those boundaries efficiently.
- When a bar shorter than the stack top arrives, the top's rectangle is complete: its height is the popped bar's height and its width is the distance to the previous stack element.
- Appending a sentinel height of 0 at the end forces all remaining bars to be resolved.
💻 Benchmark Python3 Implementation
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights = heights + [0] # sentinel flushes the stack
st = [] # indices with increasing heights
best = 0
for i, h in enumerate(heights):
while st and heights[st[-1]] >= h:
height = heights[st.pop()] # this bar's rectangle is complete
# width: from the previous smaller bar (exclusive) to i (exclusive)
width = i if not st else i - st[-1] - 1
best = max(best, height * width)
st.append(i)
return best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each index is pushed once and popped at most once.
💾 Space Complexity
O(n) for the stack (plus the sentinel copy).
⚠️ Interview Pitfalls & Follow-ups
- Omitting the sentinel: bars left on the stack at the end would never be evaluated.
- Computing the width as
i - j: the correct width excludes the previous smaller bar, so it isi - st[-1] - 1. - Using
>instead of>=in the pop condition: with equal heights either works, but>=keeps the stack strictly increasing and avoids redundant work. - Trying a two-pointer expansion per bar: O(n^2).
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Stack Problems
中文速览与面试要点
柱状图中最大的矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1。求在该柱状图中,能够勾勒出来的矩形的最大面积。约束:1 ≤ heights.length ≤ 10^5;0 ≤ heights[i] ≤ 10^4。
核心要点
- 单调递增栈(标准解) :维护一个存 下标 的栈,栈内对应的高度单调递增。
- 核心思路 :对每根柱子,以它的高度为矩形高,需要向左右扩展到「第一根比它矮的柱子」。用单调栈可以 O(n) 求出每个位置的左右边界。
- 弹栈时结算 :当遇到高度小于栈顶的柱子时,弹出栈顶下标 j,此时「以 heights[j] 为高」的矩形的左右边界已确定——左边界是弹出后新的栈顶(或 −1),右边界是当前下标 i。宽度为 i − 左边界 − 1 。
- 末尾哨兵 :在数组末尾追加高度 0,保证所有柱子都会在遍历结束时被弹出结算。
常见陷阱
- 忘记末尾哨兵 :若不加 0,遍历结束后栈中仍有元素未被结算,会漏掉以它们为高的矩形。也可以在循环外用 while stack 再结算一遍。
- 宽度公式写成 i − j :正确是 i − left − 1 (left 是左边界下标,i 是右边界下标)。
- 比较用 >= 而非 > :用 > 保证相等高度的柱子都会被结算,结果仍正确;用 >= 会提前弹出,虽然面积计算仍对但逻辑稍复杂。
- 用「枚举每个高度作为最小值 + 向两侧扩展」 :O(n²) 会超时。
- 栈中存高度而非下标 :无法计算宽度。必须存下标。
参考实现
class Solution:
def largestRectangleArea(self, heights: list[int]) -> int:
best = 0
stack = [] # 存下标,高度单调递增
# 末尾追加哨兵 0,保证所有柱子都被结算
for i, h in enumerate(heights + [0]):
while stack and heights[stack[-1]] > h:
j = stack.pop()
left = stack[-1] if stack else -1
width = i - left - 1 # 左右边界之间的距离
area = heights[j] * width
if area > best:
best = area
stack.append(i)
return best