13 Apr 2024
5 min read
The ‘Largest Rectangle in Histogram’ problem is as follows:
Given an array of integers heights representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
I love this problem as it provides an amazing introduction to problem solving, more specifically, formalizing proofs of why algorithms work. Let’s start with an example:
Let the array of heights be [1, 4, 7, 5, 7]
:
The answer is 16
:
If you have solved this problem before, or just looked at the answer, you may have found it hard to convince yourself why the algorithm works. Fret not, I am here to try formalizing the proof of the algorithm so that you can understand how exactly it works!
The general solution is to keep a monotonically increasing stack of indices
We can think of the monotonically increasing property as an invariant that the stack must maintain.
As a refresher, an invariant is a property that is always true across iterations (of a loop) or for all elements in a data structure.
A monotonically increasing stack of indices maintains the following invariants:
For each index
Many monotonic stack problems involve thinking about two key operations:
When
When
To calculate the
To derive the width of
Otherwise,
Notice that if
The above claim implies that
Suppose that
If
If
To prove this, notice that
Given that
Therefore, the claim is proven and we know that
If
Therefore, we have found both the rightmost index where
If
If
When we implement the algorithm, we see that we naturally derive the ideal stack solution:
def largestRectangleArea(self, heights: List[int]) -> int:
stack = []
heights.append(0)
n = len(heights)
ans = 0
for i in range(n):
while stack and heights[i] < heights[stack[-1]]:
j = stack.pop()
h = heights[j]
w = i if not stack else (i - stack[-1] - 1)
ans = max(ans, w * h)
stack.append(i)
return ans
There you have it! The largest rectangle in histogram algorithm has now been formally proven and the magic numbers have been answered! Of course, when working on these problems during an interview, it is not expected of you to derive these proofs from scratch, but having such an intuition about monotonic stacks help a lot in reasoning with the magic values that are used!
Enjoyed reading?
Consider subscribing to my RSS feed or reaching out to me through email!