84. Largest Rectangle in Histogram
Asked at 28Amazon61Microsoft57Google57Bloomberg56Meta46tcs57Accenture54thoughtspot77Coupang76Myntra73Visa72Flipkart68BitGo68Capital One64Waymo58Walmart Labs53DoorDash51josh technology50Uber47TikTok46Adobe44Cisco37Goldman Sachs36IBM35Infosys30Salesforce28LinkedIn27Oracle27
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
assert Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) == 10
assert Solution().largestRectangleArea([2, 4]) == 4
class Solution {
public int largestRectangleArea(int[] heights) {
Deque<Integer> st = new ArrayDeque<>();
int best = 0, n = heights.length;
for (int i = 0; i <= n; i++) {
int h = i == n ? 0 : heights[i];
while (!st.isEmpty() && heights[st.peek()] >= h) {
int top = heights[st.pop()];
int left = st.isEmpty() ? -1 : st.peek();
best = Math.max(best, top * (i - left - 1));
}
st.push(i);
}
return best;
}
}
func largestRectangleArea(heights []int) int {
st, best := []int{}, 0 // increasing stack of indices
for i := 0; i <= len(heights); i++ {
h := 0 // sentinel bar after the end
if i < len(heights) {
h = heights[i]
}
for len(st) > 0 && heights[st[len(st)-1]] >= h {
top := heights[st[len(st)-1]]
st = st[:len(st)-1]
left := -1
if len(st) > 0 {
left = st[len(st)-1]
}
best = max(best, top*(i-left-1))
}
st = append(st, i)
}
return best
}