Tutorialspoint
Problem
Solution
Submissions

Largest Rectangle in Histogram

Certification: Advanced Level Accuracy: 50% Submissions: 2 Points: 15

Write a Java program to find the largest rectangle area in a histogram. A histogram is represented as an array of integers where each element represents the height of the bar at that position. The width of each bar is 1.

Example 1
  • Input: heights = [2, 1, 5, 6, 2, 3]
  • Output: 10
  • Explanation: The maximum area can be formed by heights[2] = heights[3] = 5 with width 2. Area = 5 * 2 = 10.
Example 2
  • Input: heights = [2, 4, 5, 3, 1]
  • Output: 9
  • Explanation: For heights[3] = 3, we can extend the width to 3, creating an area of 3 * 3 = 9.
Constraints
  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4
  • Time Complexity: O(n), where n is the length of the heights array
  • Space Complexity: O(n)
ArraysStackCapgeminiPhillips
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 increasing heights in the histogram
  • When you find a bar shorter than the top of the stack, you've found a right boundary
  • Pop from the stack to get the height of the rectangle
  • The width will be the current position minus the new top of the stack minus 1
  • For each popped element, calculate the area and keep track of the maximum area
  • Process a sentinel value at the end to handle remaining elements in the stack
  • Take special care with empty stack cases

Steps to solve by this approach:

 Step 1: Initialize an empty stack and a variable to track the maximum area.

 Step 2: Iterate through each bar in the histogram, including a sentinel bar of height 0 at the end.
 Step 3: For each bar, while the current bar's height is less than the bar at the top of the stack, we've found a right boundary.
 Step 4: Pop the top bar from the stack, calculate its height, and determine its width based on the current position and the new top of the stack.
 Step 5: Calculate the area of the rectangle and update the maximum area if necessary.
 Step 6: Push the current bar's index onto the stack.
 Step 7: Return the maximum area after processing all bars.

Submitted Code :