Discover how a simple stack can save you hours of tedious work finding the biggest rectangle!
Why Largest Rectangle in Histogram Using Stack in DSA Go?
Imagine you have a row of buildings with different heights, and you want to find the largest flat area you can cover by choosing some consecutive buildings. Doing this by checking every possible group of buildings one by one is like measuring every possible rectangle manually, which takes a lot of time.
Manually checking all groups means trying every start and end point, calculating the smallest building height in that group, and then the area. This is very slow and tiring, especially if there are many buildings. It's easy to make mistakes and miss the biggest area.
Using a stack helps us keep track of building heights in a smart way. We can quickly find where a building's height stops being the smallest and calculate the largest rectangle possible without checking every group. This saves a lot of time and effort.
maxArea := 0 for i := 0; i < len(heights); i++ { for j := i; j < len(heights); j++ { minHeight := heights[i] for k := i; k <= j; k++ { if heights[k] < minHeight { minHeight = heights[k] } } area := minHeight * (j - i + 1) if area > maxArea { maxArea = area } } }
stack := []int{}
maxArea := 0
for i := 0; i <= len(heights); i++ {
currentHeight := 0
if i < len(heights) {
currentHeight = heights[i]
}
for len(stack) > 0 && currentHeight < heights[stack[len(stack)-1]] {
topIndex := stack[len(stack)-1]
stack = stack[:len(stack)-1]
width := i
if len(stack) > 0 {
width = i - stack[len(stack)-1] - 1
}
area := heights[topIndex] * width
if area > maxArea {
maxArea = area
}
}
stack = append(stack, i)
}This method lets you find the largest rectangle in a histogram quickly and efficiently, even for very tall and many buildings.
Think of a city planner who wants to find the biggest flat area in a row of buildings to build a park or a billboard. Using this stack method, they can quickly find the best spot without checking every possible area manually.
Manually checking all rectangles is slow and error-prone.
Using a stack helps track building heights smartly to find the largest rectangle fast.
This approach saves time and works well even for large histograms.
Practice
Solution
Step 1: Understand stack usage
The stack stores indices of bars in increasing height order to find boundaries efficiently.Step 2: Purpose in algorithm
This helps quickly calculate the largest rectangle when a smaller height bar is found.Final Answer:
To keep track of bars' indices with increasing heights -> Option CQuick Check:
Stack tracks increasing bars = B [OK]
- Thinking stack sorts bars by height
- Using stack to store areas instead of indices
- Ignoring the order of bars in stack
Solution
Step 1: Identify stack type
The stack holds indices, which are integers, so it should be a slice of int.Step 2: Check syntax correctness
"var stack []int" declares an empty slice of int, suitable for stack operations.Final Answer:
var stack []int -> Option AQuick Check:
Stack as []int slice = C [OK]
- Using map instead of slice for stack
- Declaring stack as int instead of slice
- Using string slice for integer indices
func largestRectangleArea(heights []int) int {
stack := []int{}
maxArea := 0
for i := 0; i <= len(heights); i++ {
var h int
if i == len(heights) {
h = 0
} else {
h = heights[i]
}
for len(stack) > 0 && h < heights[stack[len(stack)-1]] {
height := heights[stack[len(stack)-1]]
stack = stack[:len(stack)-1]
var width int
if len(stack) == 0 {
width = i
} else {
width = i - stack[len(stack)-1] - 1
}
area := height * width
if area > maxArea {
maxArea = area
}
}
stack = append(stack, i)
}
return maxArea
}
fmt.Println(largestRectangleArea([]int{2, 1, 5, 6, 2, 3}))Solution
Step 1: Trace stack and area calculation
Process bars: max area found is 10 (from bars 5 and 6 with width 2).Step 2: Confirm max area
No larger rectangle found; 10 is the largest rectangle area.Final Answer:
10 -> Option DQuick Check:
Largest rectangle area = 10 [OK]
- Forgetting to add a zero height bar at end
- Incorrect width calculation after popping stack
- Not updating maxArea correctly
for i := 0; i < len(heights); i++ {
for len(stack) > 0 && heights[i] < heights[stack[len(stack)-1]] {
height := heights[stack[len(stack)-1]]
stack = stack[:len(stack)-1]
width := i
if len(stack) > 0 {
width = i - stack[len(stack)-1] - 1
}
area := height * width
if area > maxArea {
maxArea = area
}
}
stack = append(stack, i)
}
return maxAreaSolution
Step 1: Check loop boundary
The loop misses processing the last bars fully without a sentinel zero height at the end.Step 2: Fix loop to include sentinel
Loop should run until i <= len(heights) and treat i == len(heights) as height 0 to pop all remaining bars.Final Answer:
Loop should run until i <= len(heights) with a sentinel zero height -> Option AQuick Check:
Loop boundary with sentinel zero fixes bug [OK]
- Not adding sentinel zero height
- Incorrect width calculation when stack empty
- Resetting maxArea inside loop incorrectly
Solution
Step 1: Analyze bars and stack operations
Largest rectangle is formed by bars with min height 5 spanning width 3 (indices 2 to 4: heights 5,4,5), area = 5*3 = 15.Step 2: Confirm no larger area
Other rectangles like 4*3=12 or 2*5=10 are smaller; 15 is maximum.Final Answer:
15 -> Option BQuick Check:
Max rectangle area = 15 [OK]
- Calculating width incorrectly
- Missing wider rectangle spanning multiple bars
- Not popping all bars at the end
Ready to prove it?
Pass the test and this pattern moves unknown
