Overview
Given an array of integers heights representing a histogram where each bar has width 1, find the area of the largest rectangle in the histogram.
Constraints
1 <= heights.length <= 100,0000 <= heights[i] <= 10,000
Examples
largestRectangleArea([2, 1, 5, 6, 2, 3]); // => 10 (bars 5,6 → 5×2) largestRectangleArea([2, 4]); // => 4
Solution
Reveal solution
function largestRectangleArea(heights) {
const stack = [];
let maxArea = 0;
const n = heights.length;
for (let i = 0; i <= n; i++) {
const h = i === n ? 0 : heights[i];
while (stack.length && heights[stack[stack.length - 1]] > h) {
const height = heights[stack.pop()];
const width = stack.length ? i - stack[stack.length - 1] - 1 : i;
maxArea = Math.max(maxArea, height * width);
}
stack.push(i);
}
return maxArea;
}Monotonic stack: maintain ascending heights. On pop, compute the rectangle using the popped height and the width to the new stack top.
Resources
largest-rectangle-in-histogram.js
Largest Rectangle in Histogram
hardcodingAlgorithmsStack
Overview
Given an array of integers heights representing a histogram where each bar has width 1, find the area of the largest rectangle in the histogram.
Constraints
1 <= heights.length <= 100,0000 <= heights[i] <= 10,000
Examples
largestRectangleArea([2, 1, 5, 6, 2, 3]); // => 10 (bars 5,6 → 5×2) largestRectangleArea([2, 4]); // => 4
Solution
Reveal solution
function largestRectangleArea(heights) {
const stack = [];
let maxArea = 0;
const n = heights.length;
for (let i = 0; i <= n; i++) {
const h = i === n ? 0 : heights[i];
while (stack.length && heights[stack[stack.length - 1]] > h) {
const height = heights[stack.pop()];
const width = stack.length ? i - stack[stack.length - 1] - 1 : i;
maxArea = Math.max(maxArea, height * width);
}
stack.push(i);
}
return maxArea;
}Monotonic stack: maintain ascending heights. On pop, compute the rectangle using the popped height and the width to the new stack top.
Resources
NameTopicDifficulty
103 of 103 problems