BackendML

Largest Rectangle in Histogram

Hard2 min read
The Largest Rectangle in Histogram problem requires finding the largest rectangular area that can be formed within a histogram.

Problem

Given an array of integers heights representing the heights of histogram bars, where each bar has a width of 1, find the area of the largest rectangle that can be formed within the histogram.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
heights = [2,1,5,6,2,3]
Output
10

Example 2

Input
heights = [2,4]
Output
4

Solution

This solution uses a Monotonic Stack to efficiently find the largest rectangle. The stack stores indices of bars whose heights are in increasing order.

When the current bar is shorter than the bar at the top of the stack, the taller bar can no longer extend to the right. We remove its index from the stack and calculate the rectangle using that height.

The width is determined by the current index and the new top of the stack. We add a bar with height 0 at the end to ensure that all remaining bars are processed.
class Solution {
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> stack = new Stack<>();
        int maxArea = 0;

        for (int i = 0; i <= heights.length; i++) {
            int currentHeight = i == heights.length ? 0 : heights[i];

            while (!stack.isEmpty() &&
                   currentHeight < heights[stack.peek()]) {

                int height = heights[stack.pop()];
                int width = stack.isEmpty()
                        ? i
                        : i - stack.peek() - 1;

                maxArea = Math.max(maxArea, height * width);
            }
            stack.push(i);
        }
        return maxArea;
    }
}

Complexity

Each bar is pushed onto and removed from the stack at most once. Therefore, the time complexity is O(n), where n is the number of histogram bars.

The stack can contain up to n indices in the worst case, so the extra space complexity is O(n).

Comments

No comments yet. Ask a question or share what helped.