Browse curriculum

Largest Rectangle in Histogram (LeetCode 84)

Largest Rectangle in Histogram (LeetCode 84): find the area of the largest rectangle in the histogram.

Problem Understanding

heights lists the bars of a histogram from left to right, each bar one unit wide. Return the area of the biggest rectangle that fits entirely inside the bars.

Example:

  • Input: [2, 1, 5, 6, 2, 3]
  • Output: 10 (The rectangle from index 2 to 3 with height 5 has area 5 * 2 = 10).

Algorithm Strategy

We use a Monotonic Increasing Stack.

Core Idea:
For each bar h at index i, if we know the first bar to the left that is smaller (left_limit) and the first bar to the right that is smaller (right_limit), then the maximum width for a rectangle with height h is right_limit - left_limit - 1.

One-Pass Logic:

  1. Maintain a stack of indices with increasing heights.
  2. When we encounter a bar h[i] smaller than h[stack.top()], it means h[i] is the Right Limit for h[stack.top()].
  3. Pop top. Now the New Top of the stack is the Left Limit for the popped bar.
  4. Calc Area: height * (i - stack.top() - 1).
  5. Repeat until stack rule is satisfied, then push i.

Interactive Visualization

[2, 1, 5, 6, 2, 3]

BASE -1

heights

2

0

1

1

5

2

6

3

2

4

3

5

stack · indices

-1

TOP · base

h

:

Area

:

Best

0

 

Start the stack with -1: the left edge for a bar with nothing shorter before it

Next

i = 0: h = 2

Free preview: the first 7 of 22 steps

Heights

Visualize how we pop bars when a shorter one appears, calculating potential areas.

Dry Run

Input: [2, 1, 5, 6, 2, 3]. The stack starts as [-1]; at i = 6 = n the height read is 0.

i h Pops (height × width = area) Stack after Best
- - - [-1] 0
0 2 - [-1, 0] 0
1 1 bar 0: 2 × 1 = 2 [-1, 1] 2
2 5 - [-1, 1, 2] 2
3 6 - [-1, 1, 2, 3] 2
4 2 bar 3: 6 × 1 = 6; bar 2: 5 × 2 = 10 [-1, 1, 4] 10
5 3 - [-1, 1, 4, 5] 10
6 0 bar 5: 3 × 1 = 3; bar 4: 2 × 4 = 8; bar 1: 1 × 6 = 6 [-1, 6] 10

Result: 10, bars 2 and 3, height 5.

Edge Cases & Common Mistakes

  • Increasing Seq: [1, 2, 3]. Nothing is popped while the bars are read; the extra step at i = n reads height 0 and pops them all, so no second loop is needed.
  • Single Bar: Area = height.
  • Left Limit: If stack empty after pop, left limit is conceptually -1.
  • In two dimensions: run this stack once per row of a 0/1 matrix, on the column heights of 1s ending at that row, and you have Maximal Rectangle.

Solution

Monotonic Stack O(N).

Largest Rectangle in Histogram Code
1var largestRectangleArea = function(heights) {
2 const stack = [-1];
3 let best = 0;
4 const n = heights.length;
5 for (let i = 0; i <= n; i++) {
6 const h = i === n ? 0 : heights[i];
7 while (stack[stack.length - 1] !== -1 && heights[stack[stack.length - 1]] >= h) {
8 const height = heights[stack.pop()];
9 const width = i - stack[stack.length - 1] - 1;
10 best = Math.max(best, height * width);
11 }
12 stack.push(i);
13 }
14 return best;
15};

Largest Rectangle in Histogram in Python, Java, C++, TypeScript and C

Largest Rectangle in Histogram in Python
class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        stack = [-1]
        best = 0
        n = len(heights)
        for i in range(n + 1):
            h = 0 if i == n else heights[i]
            while stack[-1] != -1 and heights[stack[-1]] >= h:
                height = heights[stack.pop()]
                width = i - stack[-1] - 1
                best = max(best, height * width)
            stack.append(i)
        return best
Largest Rectangle in Histogram in Java
class Solution {
    public int largestRectangleArea(int[] heights) {
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(-1);
        int best = 0;
        int n = heights.length;
        for (int i = 0; i <= n; i++) {
            int h = i == n ? 0 : heights[i];
            while (stack.peek() != -1 && heights[stack.peek()] >= h) {
                int height = heights[stack.pop()];
                int width = i - stack.peek() - 1;
                best = Math.max(best, height * width);
            }
            stack.push(i);
        }
        return best;
    }
}
Largest Rectangle in Histogram in C++
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> st;
        st.push(-1);
        int best = 0;
        int n = heights.size();
        for (int i = 0; i <= n; i++) {
            int h = i == n ? 0 : heights[i];
            while (st.top() != -1 && heights[st.top()] >= h) {
                int height = heights[st.top()];
                st.pop();
                int width = i - st.top() - 1;
                best = max(best, height * width);
            }
            st.push(i);
        }
        return best;
    }
};
Largest Rectangle in Histogram in TypeScript
function largestRectangleArea(heights: number[]): number {
    const stack: number[] = [-1];
    let best = 0;
    const n = heights.length;
    for (let i = 0; i <= n; i++) {
        const h = i === n ? 0 : heights[i];
        while (stack[stack.length - 1] !== -1 && heights[stack[stack.length - 1]] >= h) {
            const height = heights[stack.pop()!];
            const width = i - stack[stack.length - 1] - 1;
            best = Math.max(best, height * width);
        }
        stack.push(i);
    }
    return best;
}
Largest Rectangle in Histogram in C
int largestRectangleArea(int* heights, int heightsSize) {
    int* stack = malloc((heightsSize + 2) * sizeof(int));
    int top = 0;
    stack[top] = -1;
    int best = 0;
    int n = heightsSize;
    for (int i = 0; i <= n; i++) {
        int h = i == n ? 0 : heights[i];
        while (stack[top] != -1 && heights[stack[top]] >= h) {
            int height = heights[stack[top--]];
            int width = i - stack[top] - 1;
            if (height * width > best) best = height * width;
        }
        stack[++top] = i;
    }
    free(stack);
    return best;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start with -1

    Put -1 on the stack as the left edge for the first bar.

  2. Pop and measure

    For i from 0 to n, while the top bar is at least the current height, pop it and compute height × (i − new top − 1).

  3. Push and repeat

    Push i and keep the largest area.

Frequently asked questions

How does the stack find each bar's rectangle?

Bars on the stack increase in height. When a bar at i is not taller than the top, the top can extend no further right, and the bar below it on the stack is where it stops on the left, so its width is i minus that index minus 1.


Why read a height of 0 after the last bar?

Bars still on the stack at the end also need measuring. A zero-height bar at i = n is shorter than all of them, so it pops every one without a second loop.


What is the time complexity?

O(n): each index is pushed once and popped once. The stack takes O(n) space.

New to the technique behind this problem? Watch it run step by step:

Stack Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description