Tutorialspoint
Problem
Solution
Submissions

Largest Rectangle in Histogram

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the area of the largest rectangle that can be formed in a histogram. Given an array of integers representing the heights of bars in a histogram where the width of each bar is 1, find the area of the largest rectangle that can be formed within the bounds of the histogram.

Example 1
  • Input: heights = [2,1,5,6,2,3]
  • Output: 10
  • Explanation:
    • The largest rectangle can be formed using bars at indices 2 and 3 with heights 5 and 6.
    • The minimum height between these bars is 5.
    • Rectangle area = min_height * width = 5 * 2 = 10.
    • Therefore, the largest rectangle area is 10.
Example 2
  • Input: heights = [2,4]
  • Output: 4
  • Explanation:
    • We can form rectangles of area 2*2=4 using the second bar, or 2*1=2 using the first bar.
    • The largest rectangle uses the bar of height 4 with width 1.
    • Rectangle area = 4 * 1 = 4.
    • Therefore, the largest rectangle area is 4.
Constraints
  • 1 ≤ heights.length ≤ 10^5
  • 0 ≤ heights[i] ≤ 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StackGoldman SachsTutorix
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 histogram bars
  • For each bar, if it's higher than the bar at the top of stack, push its index
  • If current bar is lower, pop from stack and calculate area with popped bar as the smallest
  • The width is determined by the current index and the index after the new top of stack
  • Continue until all bars are processed and stack is empty
  • Keep track of the maximum area found during the process

Steps to solve by this approach:

 Step 1: Initialize a stack to store indices and variables for tracking maximum area.

 Step 2: Iterate through each bar in the histogram from left to right.
 Step 3: If current bar is taller than the bar at stack top, push current index to stack.
 Step 4: If current bar is shorter, pop from stack and calculate area using popped bar as height.
 Step 5: Calculate width as difference between current index and new stack top.
 Step 6: Update maximum area if current calculated area is larger.
 Step 7: After processing all bars, pop remaining indices and calculate their areas.

Submitted Code :