Algorithm Day74 - Largest Rectangle in Histogram
🧩 Problem Description
Given an array of integers heights
representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
💬 Examples
Example 1
1 | Input: heights = [2,1,5,6,2,3] |
Example 2
1 | Input: heights = [2,4] |
💡 Intuition
We want to find the largest rectangle area in a histogram.
A monotonic increasing stack helps track the left and right boundaries for each bar:
- Traverse the bars.
- While current height is less than the top of stack, pop from stack and calculate area.
- Area = poppedHeight * (currentIndex - stackTopAfterPop - 1).
- Push current index onto the stack.
- Add sentinel 0 at the end to flush out remaining bars.
🔢 Java Code (Monotonic Stack)
1 | import java.util.*; |
⏱ Complexity Analysis
- Time: O(n) — each bar pushed and popped at most once.
- Space: O(n) — stack storage.
✍️ Summary
- Use monotonic increasing stack to efficiently compute rectangle areas.
- Each bar defines a rectangle extended until a smaller bar appears.
Related problems
lc-85
— Maximal Rectanglelc-42
— Trapping Rain Waterlc-239
— Sliding Window Maximum