</>

84. Largest Rectangle in Histogram

Hard NeetCode 150
Stack Time O(N) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Stack
Time
O(N)
Space
O(N)

Standard Solution (C++)

SummaryGiven an array of bar heights forming a histogram, find the area of the largest axis-aligned rectangle that can be formed using one or more consecutive bars.

Approach
  • Maintain a monotonically increasing stack of bar indices; each entry represents a bar that could still be the shortest bar in some future rectangle.
  • When a shorter bar is encountered, every taller bar popped from the stack becomes the height of a candidate rectangle whose right boundary is the current index and whose left boundary is the new stack top.
  • Appending a sentinel height of 0 at the end forces all remaining bars to be popped and evaluated without a separate post-loop pass.
  • Each bar is pushed and popped at most once, giving linear time overall.
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        // Sentinel at the end ensures every bar is eventually popped.
        heights.push_back(0);

        stack<int> stk;  // monotonically increasing stack of indices
        int maxArea = 0;

        for (int i = 0; i < (int)heights.size(); ++i) {
            // Pop all bars taller than the current one.
            while (!stk.empty() && heights[stk.top()] > heights[i]) {
                int h = heights[stk.top()];
                stk.pop();
                // Left boundary: top of stack after pop (-1 if empty means left wall).
                int leftBound = stk.empty() ? -1 : stk.top();
                int width = i - leftBound - 1;
                maxArea = max(maxArea, h * width);
            }
            stk.push(i);
        }

        // Restore the input array (remove the sentinel).
        heights.pop_back();
        return maxArea;
    }
};
Time O(n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        // use monotonic stack
        // the stack stores the index of bars
        stack<int> s;
        int maxArea=0;

        // key details
        s.push(-1);
        heights.push_back(0);

        for(int i=0; i<heights.size(); ++i){
            while(s.top()!=-1 && heights[i]<=heights[s.top()]){
                int height=heights[s.top()];
                s.pop();
                
                int left=s.top();
                int width=(i-1)-left;
                maxArea=std::max(maxArea, width*height);
            }
            s.push(i);
        }

        return maxArea;
    }
};

// Time Complexity: O(N). Each bar is pushed and popped exactly once.
// Space Complexity: O(N). The stack can contain at most N elements.
Time O(N) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern