Largest rectangle in a histogram
The problem
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.
Input: heights = [2, 1, 5, 6, 2, 3]
Output: 10
Explanation: The largest rectangle is highlighted, which has an area of 5*2 = 10 units.
Input: heights = [3, 5, 1, 7, 5, 9]
Output: 15
Explanation: The largest rectangle has an area of 5*3 = 15 units.
Input: heights = [2,4]
- 1 <= heights.length <= 105
- 0 <= heights[i] <= 104
cpp
class Solution
{
public:
int largestRectangleArea(vector<int> &heights) {
}
};java
class Solution {
public int largestRectangleArea(int[] heights) {
}
}python
class Solution:
def largestRectangleArea(self, heights):javascript
class Solution {
largestRectangleArea(heights) {
}
}csharp
public class Solution
{
public int LargestRectangleArea(List<int> heights)
{
}
}go
func largestRectangleArea(heights []int) int {
}Stuck? Show a way to structure it+
- 01Append an implicit zero-height sentinel.
- 02Keep indices with increasing heights.
- 03When a lower bar arrives, pop taller bars.
- 04Compute width from new stack top to current index.
- 05Update the best area for each popped bar.
Reference answer
Then expect these follow-ups
How would you return rectangle boundaries as well as area?
Tests: implementation extension
Why is each stack operation amortized O(1)?
Tests: correctness reasoning
Hiring now
Porter is hiring right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Full Cycle Account Executive
Remote
Frontend Engineer
New York, NY, US
Backend Engineer (Go)
New York City
Next question