Question presented to candidate: "You are given a list of bar heights for a histogram where every bar is 1 unit wide. Find the area of the largest rectangle that fits inside the bars. Start with any working idea, then get it to linear time. Please write it in Python."
What a strong answer should cover:
- The rectangle's height is the shortest bar it covers, so each bar's best rectangle spans from its previous smaller bar to its next smaller bar.
- A monotonic stack of indices (heights increasing) finds both edges at the moment a bar is popped; width is
i - stack[-1] - 1oriwhen the stack is empty. - O(n) time because each index is pushed and popped once; O(n) extra space for the stack; the O(n^2) brute force as a warm-up.
- A sentinel height 0 at the end (or a final clean-up loop) so bars still on the stack are counted.
- Python specifics: a plain
listis the stack (append/pop/[-1]),stack[-1]on an empty list raisesIndexError, and Python ints never overflow.
Clarifying questions expected:
- "Can heights be 0, and can the list be empty?"
- "Do you want only the area, or the bounds of the rectangle too?"
Code / implementation expected: Yes โ largest_rectangle(heights) in Python with a list used as a stack, ideally in one pass with a sentinel.