LeetCode 84: Largest Rectangle in Histogram Solution

Master LeetCode problem 84 (Largest Rectangle in Histogram), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

84. Largest Rectangle in Histogram

Problem Explanation

Explanation

To solve this problem, we can use a stack to keep track of the indices of the bars in the histogram. We iterate through the histogram and for each bar, we check if its height is greater than the height of the bar at the index on top of the stack. If it is, we push the current index onto the stack. If not, we keep popping indices from the stack and calculate the area of the rectangle formed by the popped bar as the smallest bar and the current bar. We keep track of the maximum area found so far.

At the end of the iteration, we may still have some bars left in the stack. We continue popping bars from the stack and calculate the area until the stack is empty.

Time complexity: O(n) where n is the number of bars in the histogram. Space complexity: O(n) where n is the number of bars in the histogram.

Solution Code

class Solution {
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> stack = new Stack<>();
        int maxArea = 0;
        for (int i = 0; i <= heights.length; i++) {
            int currHeight = (i == heights.length) ? 0 : heights[i];
            while (!stack.isEmpty() && currHeight < 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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 84 (Largest Rectangle in Histogram)?

This page provides optimized solutions for LeetCode problem 84 (Largest Rectangle in Histogram) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 84 (Largest Rectangle in Histogram)?

The time complexity for LeetCode 84 (Largest Rectangle in Histogram) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 84 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 84 in Java, C++, or Python.

Back to LeetCode Solutions