Tutorialspoint
Problem
Solution
Submissions

Largest Rectangle in Histogram

Certification: Advanced Level Accuracy: 40% Submissions: 5 Points: 12

Write a C++ program to find the largest rectangle in a histogram. Given an array of integers heights representing the histogram's bar heights where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Example 1
  • Input: heights = [2, 1, 5, 6, 2, 3]
  • Output: 10
  • Explanation:
    • Step 1: Iterate through each bar in the histogram.
    • Step 2: For each bar, calculate the largest rectangle that can include this bar.
    • Step 3: The largest rectangle has an area of 10 units, formed by bars at indices 2-3 with height 5.
    • Step 4: Return the maximum area found.
Example 2
  • Input: heights = [2, 4, 5, 3, 1]
  • Output: 9
  • Explanation:
    • Step 1: Iterate through each bar in the histogram.
    • Step 2: For each bar, calculate the largest rectangle that can include this bar.
    • Step 3: The largest rectangle has an area of 9 units, formed by bars at indices 1-3 with height 3.
    • Step 4: Return the maximum area found.
Constraints
  • 1 ≤ heights.length ≤ 10^5
  • 0 ≤ heights[i] ≤ 10^4
  • Time Complexity: O(n) where n is the number of bars
  • Space Complexity: O(n)
ArraysStackGoogleTCS (Tata Consultancy Services)
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a stack to keep track of indices of bars in non-decreasing order of height
  • When you find a bar shorter than the one at the top of the stack, you can calculate areas
  • The width of the rectangle is determined by the distance between the current bar and the bar just before the popped bar
  • Continue popping bars and calculating areas until you find a shorter bar or the stack is empty
  • Remember to process remaining bars in the stack after scanning the entire array

Steps to solve by this approach:

 Step 1: Initialize an empty stack to keep track of indices of bars in non-decreasing order of height
 Step 2: Iterate through each bar in the histogram (including a sentinel value at the end)
 Step 3: While the current bar is shorter than the bar at the top of the stack, pop the top element
 Step 4: Calculate the area of rectangle with the popped bar as the shortest bar
 Step 5: The width is determined by the current index and the index of the element below the popped element
 Step 6: Update the maximum area if the calculated area is larger
 Step 7: Push the current index onto the stack and continue

Submitted Code :