Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the largest rectangle that fits under a histogram of bar heights.

Problem: Find the largest rectangle that fits under a histogram of bar heights.
def largest(h):
    st, best = [], 0
    for i, x in enumerate(h + [0]):
        while st and h[st[-1]] >= x:
            height = h[st.pop()]
            left = st[-1] + 1 if st else 0
            best = max(best, height * (i - left))
        st.append(i)
    return best
print(largest([2, 1, 5, 6, 2, 3]), largest([3, 3, 3]))
What is printed?
  1. A. 10 9
  2. B. 12 9
  3. C. 10 3
  4. D. 6 9

Correct answer: A. 10 9

When a bar is popped, the bar now on top is its first smaller bar on the left and i is the first smaller on the right, so its widest rectangle is known. 5 and 6 together give 5 × 2 = 10. The appended 0 flushes the stack at the end – without it [3, 3, 3] would return 0. O(n).

More Coding Interview Problems questions

Exams that ask this topic