allizwell.jobsdoor360.in

Largest Rectangle in Histogram

Data Structures and Algorithms / Stacks and Queues / Largest Rectangle in Histogram

Largest Rectangle in Histogram

The Largest Rectangle in Histogram problem is a popular stack-based problem in Data Structures and Algorithms. Given an array representing the heights of histogram bars, our task is to find the maximum rectangular area that can be formed using consecutive bars. We solve this problem efficiently using a Monotonic Increasing Stack.

1. What Is a Histogram?

A histogram consists of a collection of rectangular bars placed next to each other. Every bar has a specific height, and every bar has the same width, usually considered to be 1 unit.

For example, consider the following array:

heights = {2, 1, 5, 6, 2, 3};

Each array element represents the height of one histogram bar. We need to select consecutive bars and form a rectangle whose height cannot exceed the shortest selected bar.

2. Understanding the Problem

Given an array of non-negative integers representing histogram bar heights, find the maximum rectangular area possible.

Example

Input:

heights = {2, 1, 5, 6, 2, 3};

Output:

10

The maximum rectangle is formed using the bars with heights 5 and 6. The rectangle has a height of 5 and a width of 2.

Area = 5 × 2 = 10.

3. Formula for Rectangle Area

The area of a rectangle is calculated using:

Area = Height × Width

In a histogram, if we choose a bar at index i as the minimum-height bar, we can extend the rectangle to the left and right until we encounter a bar that is smaller than heights[i].

Therefore:

Width = Right Smaller Index - Left Smaller Index - 1

Area = heights[i] × Width

The largest rectangle is the maximum area calculated for all bars.

4. Important Concept: Nearest Smaller Elements

To calculate the largest rectangle efficiently, we need to find two boundaries for each bar:

  • Nearest Smaller to Left: The closest index on the left whose height is smaller than the current bar.
  • Nearest Smaller to Right: The closest index on the right whose height is smaller than the current bar.

These two boundaries tell us how far a rectangle of the current bar's height can extend.

Important: If no smaller bar exists on the left, use -1. If no smaller bar exists on the right, use n, where n is the total number of bars.

5. Brute Force Approach

The simplest approach is to consider every possible starting index and extend the rectangle towards the right.

While extending, maintain the minimum height encountered so far. For every extension, calculate the area.

Algorithm

  1. Choose each bar as the starting position.
  2. Move towards the right, one bar at a time.
  3. Maintain the minimum height in the current range.
  4. Calculate the rectangle area using the minimum height and range width.
  5. Update the maximum area.

C++ Implementation

#include <bits/stdc++.h>
using namespace std;

int largestRectangleArea(vector<int>& heights) {
    int n = heights.size();
    int maxArea = 0;

    for (int i = 0; i < n; i++) {
        int minHeight = INT_MAX;

        for (int j = i; j < n; j++) {
            minHeight = min(minHeight, heights[j]);

            int width = j - i + 1;
            int area = minHeight * width;

            maxArea = max(maxArea, area);
        }
    }

    return maxArea;
}

int main() {
    vector<int> heights = {2, 1, 5, 6, 2, 3};

    cout << largestRectangleArea(heights);

    return 0;
}

Output: 10

Complexity Analysis

  • Time Complexity: O(n²), because we examine all possible ranges.
  • Space Complexity: O(1), because we use only a few additional variables.

This approach is easy to understand but becomes inefficient for large arrays.

6. Optimized Approach Using a Monotonic Stack

We can solve this problem in O(n) time using a stack that maintains indices of bars in increasing order of their heights.

The stack helps us identify when a bar can no longer extend its rectangle towards the right.

How the Stack Works

  1. Traverse the histogram from left to right.
  2. Push the current index if its height is greater than or equal to the height at the stack's top index.
  3. If the current height is smaller, pop indices from the stack.
  4. For every popped index, calculate its maximum possible rectangle.
  5. Continue until the stack is empty or the top bar is smaller than the current bar.
  6. After processing all bars, process the remaining stack using the end of the histogram as a smaller boundary.

Why Do We Use a Monotonic Increasing Stack?

The stack stores indices in such a way that their corresponding heights are in non-decreasing order.

When we find a smaller height, it means that the popped bar cannot extend its rectangle beyond the current position. We can now calculate its maximum possible area.

7. Optimized C++ Implementation

#include <bits/stdc++.h>
using namespace std;

int largestRectangleArea(vector<int>& heights) {
    int n = heights.size();

    stack<int> st;
    int maxArea = 0;

    for (int i = 0; i <= n; i++) {

        int currentHeight = (i == n) ? 0 : heights[i];

        while (!st.empty() &&
               heights[st.top()] > currentHeight) {

            int height = heights[st.top()];
            st.pop();

            int width;

            if (st.empty()) {
                width = i;
            } else {
                width = i - st.top() - 1;
            }

            int area = height * width;

            maxArea = max(maxArea, area);
        }

        if (i < n) {
            st.push(i);
        }
    }

    return maxArea;
}

int main() {
    vector<int> heights = {2, 1, 5, 6, 2, 3};

    cout << "Largest Rectangle Area: "
         << largestRectangleArea(heights);

    return 0;
}

Largest Rectangle Area: 10

8. Understanding the Optimized Code

Step 1: Create a Stack

stack<int> st;

We use a stack to store indices of histogram bars rather than storing their heights directly. Indices help us calculate rectangle widths.

Step 2: Process Every Bar

for (int i = 0; i <= n; i++)

We process all bars and one additional position at index n. This additional position acts as a smaller-height boundary to ensure that all remaining bars are processed.

Step 3: Remove Taller Bars

while (!st.empty() &&
       heights[st.top()] > currentHeight)

If the current bar is shorter than the bar at the top of the stack, the taller bar cannot extend any further to the right. Therefore, we pop it and calculate its maximum rectangle.

Step 4: Calculate Height

int height = heights[st.top()];
st.pop();

The popped bar becomes the limiting height of the rectangle.

Step 5: Calculate Width

if (st.empty()) {
    width = i;
} else {
    width = i - st.top() - 1;
}

The current index i is the first smaller bar on the right. After popping, the new stack top is the nearest smaller bar on the left.

If the stack is empty, no smaller bar exists on the left, so the rectangle starts at index 0.

Step 6: Update Maximum Area

int area = height * width;
maxArea = max(maxArea, area);

Calculate the area and update the maximum result whenever a larger rectangle is found.

9. Dry Run of the Optimized Algorithm

Consider the following input:

heights = {2, 1, 5, 6, 2, 3}

We maintain a stack of indices. The stack's heights remain in non-decreasing order.

Current Index Current Height Operation Maximum Area
0 2 Push index 0 0
1 1 Pop height 2; area = 2 × 1 = 2. Push index 1 2
2 5 Push index 2 2
3 6 Push index 3 2
4 2 Pop height 6: area = 6 × 1 = 6. Pop height 5: area = 5 × 2 = 10. Push index 4 10
5 3 Push index 5 10
6 (extra) 0 Pop remaining bars and calculate their areas 10

The largest area found during the execution is 10.

Important Calculation

When index 4 with height 2 is processed, the bar with height 5 is popped.

  • Height = 5
  • Nearest smaller index on the left = 1
  • Nearest smaller index on the right = 4
  • Width = 4 - 1 - 1 = 2

Area = 5 × 2 = 10.

10. Complexity Analysis

Approach Time Complexity Auxiliary Space
Brute Force O(n²) O(1)
Monotonic Stack O(n) O(n)

The optimized approach takes O(n) time because every index is pushed onto the stack once and popped at most once.

11. Edge Cases

Case 1: Empty Histogram

heights = {}

Output: 0

Case 2: Only One Bar

heights = {5}

Output: 5

Case 3: All Bars Have Equal Height

heights = {3, 3, 3, 3}

The rectangle can cover all four bars.

Output: 12

Case 4: Increasing Heights

heights = {1, 2, 3, 4, 5}

Output: 9

Case 5: Decreasing Heights

heights = {5, 4, 3, 2, 1}

Output: 9

Case 6: All Heights Are Zero

heights = {0, 0, 0}

Output: 0

12. Common Mistakes

  • Storing heights instead of indices: Indices are needed to calculate the width of a rectangle.
  • Incorrect width formula: Remember that width is right boundary minus left boundary minus one.
  • Forgetting the extra iteration: Without processing a smaller sentinel height, remaining bars may never be popped.
  • Incorrect boundary handling: If the stack becomes empty after popping, the rectangle starts from index 0.
  • Ignoring duplicate heights: Equal heights must be handled consistently. The implementation above uses a strict greater-than comparison when popping.
  • Using the wrong area: Always multiply the popped bar's height by its maximum valid width.

13. Applications

  • Finding the largest rectangular area in histogram data.
  • Image processing and rectangular region detection.
  • Solving the maximal rectangle problem in binary matrices.
  • Understanding nearest smaller element problems.
  • Optimizing problems involving ranges and minimum values.

14. Interview Questions

  1. What is the Largest Rectangle in Histogram problem?
  2. Why is a stack useful for solving this problem?
  3. What is a Monotonic Increasing Stack?
  4. Why do we store indices instead of heights?
  5. How do we calculate the width of a rectangle?
  6. Why do we process an additional index after the last bar?
  7. What is the time complexity of the optimized solution?
  8. How can this problem be extended to find the maximal rectangle in a binary matrix?

15. Practice Problems

  1. Find the largest rectangle in a histogram containing only equal-height bars.
  2. Find the largest rectangle for an increasing array of heights.
  3. Find the largest rectangle for a decreasing array of heights.
  4. Implement the solution using separate nearest-smaller-left and nearest-smaller-right arrays.
  5. Solve the Maximal Rectangle problem in a binary matrix using the histogram technique.

16. Summary

  • A histogram contains consecutive bars with different heights.
  • The goal is to find the maximum rectangular area.
  • The area is calculated as height multiplied by width.
  • Nearest smaller elements determine the boundaries of a rectangle.
  • A Monotonic Increasing Stack helps find these boundaries efficiently.
  • The optimized solution takes O(n) time and O(n) auxiliary space.
Key Takeaway: Whenever a problem asks for the largest rectangle in a histogram, think about nearest smaller elements and a Monotonic Stack. This technique reduces the brute-force O(n²) solution to O(n).
Scroll to Top