84. Largest Rectangle in Histogram
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the area of the largest rectangle that can be inscribed in a histogram. The histogram is given as an array of integers representing bar heights, with each bar having a width of 1.
Solution
Largest Rectangle in Histogram in Python
class Solution:
def largestRectangleArea(self, heights: list[int]) -> int:
stack = [] # The stack will store indices of the bars.
max_area = 0
# Add a sentinel bar of height 0 at the end to process all bars in the stack.
heights_with_sentinel = heights + [0]
n = len(heights_with_sentinel)
for i in range(n):
current_height = heights_with_sentinel[i]
# While stack is not empty and current bar is shorter than the bar at stack's top.
while stack and current_height < heights_with_sentinel[stack[-1]]:
# Pop the stack top. This bar's height is the height of the rectangle.
h = heights_with_sentinel[stack.pop()]
# Calculate the width.
# Right boundary is the current index 'i'.
# Left boundary is the index of the element now at the top of the stack.
# If stack is empty, the rectangle extends to the beginning.
w = i if not stack else i - stack[-1] - 1
# Update max_area
max_area = max(max_area, h * w)
# Push the current index onto the stack.
stack.append(i)
return max_area
Largest Rectangle in Histogram in Java
class Solution {
public int largestRectangleArea(int[] heights) {
// Stack will store indices of the bars.
Stack<Integer> stack = new Stack<>();
int maxArea = 0;
int n = heights.length;
// Iterate through each bar, plus a virtual bar at the end
for (int i = 0; i <= n; i++) {
// Use 0 as the height for the virtual bar at the end (sentinel).
// This ensures all bars in the stack are processed.
int currentHeight = (i == n) ? 0 : heights[i];
// While stack is not empty and the bar at stack's top is taller than the current bar
while (!stack.isEmpty() && currentHeight < heights[stack.peek()]) {
// Pop the stack top. This bar's height is the height of the rectangle.
int h = heights[stack.pop()];
// Calculate the width.
// Right boundary is the current index 'i'.
// Left boundary is the index of the element now at the top of the stack.
// If stack is empty, it means this bar can extend to the very beginning.
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
// Update maxArea
maxArea = Math.max(maxArea, h * w);
}
// Push the current index onto the stack.
stack.push(i);
}
return maxArea;
}
}
Largest Rectangle in Histogram in C++
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> st;
int max_area = 0;
int n = heights.size();
// Iterate through each bar, plus a virtual bar at the end
for (int i = 0; i <= n; ++i) {
// Use 0 as the height for the virtual bar at the end
// This ensures all bars in the stack are processed
int current_height = (i == n) ? 0 : heights[i];
// While stack is not empty and current bar is shorter than the bar at stack's top
while (!st.empty() && current_height < heights[st.top()]) {
// Pop the stack top. This bar's height determines the rectangle's height.
int h = heights[st.top()];
st.pop();
// Calculate the width.
// Right boundary is the current index 'i'.
// Left boundary is the index of the element now at the top of the stack.
// If stack is empty, it means this bar can extend to the very beginning (index -1).
int w = st.empty() ? i : i - st.top() - 1;
// Update max_area
max_area = max(max_area, h * w);
}
// Push current bar's index onto the stack
st.push(i);
}
return max_area;
}
};
Largest Rectangle in Histogram in TypeScript
function largestRectangleArea(heights: number[]): number {
const stack: number[] = []; // Stack stores indices
let maxArea = 0;
const n = heights.length;
// Iterate through each bar, plus a virtual bar at the end (i <= n)
for (let i = 0; i <= n; i++) {
// Get current height. Use 0 if we are past the end of the array (sentinel).
const currentHeight = (i === n) ? 0 : heights[i];
// While stack is not empty and the bar at stack's top is taller than the current bar
while (stack.length > 0 && currentHeight < heights[stack[stack.length - 1]]) {
// Pop the stack top. This bar's height is the height of the rectangle.
// The non-null assertion `!` is safe because we checked `stack.length > 0`.
const h = heights[stack.pop()!];
// Calculate the width.
// Right boundary is the current index 'i'.
// Left boundary is the index of the element now at the top of the stack.
// If stack is empty, it means this bar can extend to the very beginning.
const w = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;
// Update maxArea
maxArea = Math.max(maxArea, h * w);
}
// Push the current index onto the stack.
stack.push(i);
}
return maxArea;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.