The Largest Rectangle in Histogram coding problem is a classic algorithmic challenge. You are given an array of integers representing the heights of bars in a histogram, where the width of each bar is 1. You need to find the area of the largest rectangle that can be formed within the bounds of this histogram.
This is a high-frequency "Hard" question asked by nearly every top-tier tech firm, from Google to Meta. It tests a candidate's ability to use advanced data structures like the Monotonic Stack to achieve a linear time solution. It requires deep logical reasoning to understand how to maintain a stack of "increasing" bars to efficiently calculate the potential area for each height.
The optimal pattern for this problem is the Monotonic Stack interview pattern. We iterate through the bars and maintain a stack of indices whose heights are in non-decreasing order. When we encounter a bar shorter than the one at the top of the stack, it means the bar at the top has reached its maximum possible width to the right. We pop it and calculate its area using the current index and the index of the new top of the stack as boundaries.
Heights: [2, 1, 5, 6, 2, 3].
Many candidates try a brute-force O(N²) solution by checking every pair of bars, which is too slow. Another common mistake is failing to handle the bars remaining on the stack after the main loop finishes (often solved by appending a 0 to the end of the heights array). Incorrectly calculating the width of the rectangle when popping from the stack is also a frequent source of bugs.
Mastering "Stack, Monotonic Stack interview pattern" questions is essential for high-level interviews. Practice visualizing the stack as a "boundary" finder. Each pop event tells you that the current element is the right boundary and the element under the popped one is the left boundary for the popped height.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Visible People in a Queue | Hard | Solve | |
| Number of Valid Subarrays | Hard | Solve | |
| Next Greater Element II | Medium | Solve | |
| Daily Temperatures | Medium | Solve | |
| Sum of Subarray Ranges | Medium | Solve |