📖 Scenario: Imagine you have a row of buildings of different heights. You want to find the largest rectangular area that can fit inside the skyline formed by these buildings.
🎯 Goal: Build a program that finds the largest rectangle area in a histogram using a stack to keep track of building heights.
📋 What You'll Learn
Create a list called heights with exact building heights
Create an empty list called stack to store indices
Use a for loop with variable i to iterate over range(len(heights) + 1)
Print the largest rectangle area as an integer
💡 Why This Matters
🌍 Real World
Finding the largest rectangle in a histogram helps in image processing, stock market analysis, and land area calculations.
💼 Career
This algorithm is often asked in coding interviews and is useful for roles involving algorithm design and optimization.
Progress0 / 4 steps
1
Create the histogram heights list
Create a list called heights with these exact values: 2, 1, 5, 6, 2, 3
DSA Python
Hint
Use square brackets and separate numbers with commas.
2
Initialize the stack and max_area variable
Create an empty list called stack and a variable called max_area set to 0
DSA Python
Hint
Use [] for an empty list and assign 0 to max_area.
3
Use a for loop to find the largest rectangle
Use a for loop with variable i to iterate over range(len(heights) + 1). Inside the loop, use a while loop to pop from stack while stack is not empty and either i == len(heights) or heights[i] <= heights[stack[-1]]. Calculate the area for each popped index and update max_area if the area is larger. Append i to stack if the while loop ends.
DSA Python
Hint
Use a for loop with range(len(heights) + 1) and a while loop inside to pop from stack and calculate areas.
4
Print the largest rectangle area
Print the value of max_area to display the largest rectangle area
DSA Python
Hint
Use print(max_area) to show the result.
Practice
(1/5)
1. What is the main purpose of using a stack in the Largest Rectangle in Histogram problem?
easy
A. To reverse the order of bars for easier calculation
B. To store the heights of all bars in sorted order
C. To keep track of bars' indices with increasing heights
D. To count the total number of bars in the histogram
Solution
Step 1: Understand the role of the stack
The stack is used to store indices of bars in increasing height order to efficiently find the largest rectangle.
Step 2: Explain why increasing order is important
When a bar with smaller height appears, we pop from the stack to calculate areas with bars taller than the current one.
Final Answer:
To keep track of bars' indices with increasing heights -> Option C
Quick Check:
Stack stores indices in increasing height order [OK]
Hint: Stack stores indices of increasing height bars [OK]
Common Mistakes:
Thinking stack stores heights instead of indices
Assuming stack sorts bars by height
Using stack to count bars instead of track indices
2. Which of the following Python code snippets correctly initializes an empty stack for the Largest Rectangle in Histogram algorithm?
easy
A. stack = ()
B. stack = {}
C. stack = None
D. stack = []
Solution
Step 1: Identify correct data structure for stack
In Python, a list is commonly used as a stack because it supports append() and pop() operations.
Step 2: Check each option
stack = [] uses a list ([]), which is correct. stack = {} uses a dictionary ({}), not suitable. stack = None assigns None, not a stack. stack = () uses a tuple (()), which is immutable.
Final Answer:
stack = [] -> Option D
Quick Check:
List [] is correct stack initialization [OK]
Hint: Use list [] for stack in Python [OK]
Common Mistakes:
Using dictionary {} instead of list
Using tuple () which is immutable
Assigning None instead of a list
3. What is the output of the following code snippet for the histogram heights = [2, 1, 5, 6, 2, 3]?
def largest_rectangle_area(heights):
stack = []
max_area = 0
for i, h in enumerate(heights + [0]):
while stack and heights[stack[-1]] > h:
height = heights[stack.pop()]
width = i if not stack else i - stack[-1] - 1
max_area = max(max_area, height * width)
stack.append(i)
return max_area
print(largest_rectangle_area([2, 1, 5, 6, 2, 3]))
medium
A. 10
B. 12
C. 8
D. 6
Solution
Step 1: Trace the stack and area calculation
Iterate through heights with an extra 0 at the end to pop all bars. The largest rectangle area found is 10 (from bars with heights 5 and 6).
Step 2: Confirm max area calculation
The max area is calculated as max(10, others), so final answer is 10.
Final Answer:
10 -> Option A
Quick Check:
Largest rectangle area = 10 [OK]
Hint: Add zero height at end to pop all bars [OK]
Common Mistakes:
Forgetting to add zero at end of heights
Incorrect width calculation
Not popping all bars from stack
4. Find the error in this code snippet for Largest Rectangle in Histogram:
def largest_rectangle_area(heights):
stack = []
max_area = 0
for i, h in enumerate(heights + [0]):
while stack and heights[stack[-1]] >= h:
height = heights[stack.pop()]
width = i - stack[-1] - 1
max_area = max(max_area, height * width)
stack.append(i)
return max_area
print(largest_rectangle_area([2, 1, 5, 6, 2, 3]))
medium
A. Width calculation should be i - stack[-1] - 1
B. Missing adding zero height at end of heights
C. Comparison should be > instead of >=
D. Stack should store heights, not indices
Solution
Step 1: Identify width calculation mistake
Width is calculated as i - stack[-1], but it should be i - stack[-1] - 1 to exclude the popped bar's index.
Step 2: Confirm other parts
Adding zero at end is optional but common; comparison >= is acceptable; stack stores indices correctly.
Final Answer:
Width calculation should be i - stack[-1] - 1 -> Option A
Quick Check:
Width = i - stack[-1] - 1 [OK]
Hint: Width = current index - previous stack top - 1 [OK]
Common Mistakes:
Incorrect width calculation causing wrong area
Forgetting to add zero at end (optional)
Confusing stack contents (indices vs heights)
5. Given the histogram heights = [6, 2, 5, 4, 5, 1, 6], what is the largest rectangle area using the stack approach?
hard
A. 10
B. 15
C. 12
D. 8
Solution
Step 1: Use stack to find largest rectangle
Traverse bars with an extra 0 at end. The largest rectangle is formed by heights 5, 4, 5 spanning width 3, area = 12, but a larger rectangle is formed by heights 6 spanning width 2, area = 12, and also by heights 6 spanning width 1, area = 6. However, the maximum area is 15 formed by heights 5, 4, 5, 1, 6 combined correctly.
Step 2: Confirm no larger area exists
After careful calculation, the largest rectangle area is 15 (from bars at indices 2 to 4 with height 5).
Final Answer:
15 -> Option B
Quick Check:
Max area = 15 from bars 5,4,5 [OK]
Hint: Check rectangles formed by popped bars for max area [OK]
Common Mistakes:
Ignoring width when calculating area
Not adding zero height at end to pop all bars
Miscomputing width boundaries
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.