Data Structures & AlgorithmsHardProduct Company SDE · stack round

Problem: What is the largest rectangle area that can be formed in a histogram of heights [2, 1, 5, 6, 2, 3]? Use the stack code.

Problem: What is the largest rectangle area that can be formed in a histogram of heights [2, 1, 5, 6, 2, 3]? Use the stack code.
h = [2, 1, 5, 6, 2, 3] + [0]
st = []
best = 0
for i, x in enumerate(h):
    start = i
    while st and st[-1][1] >= x:
        j, y = st.pop()
        best = max(best, y * (i - j))
        start = j
    st.append((start, x))
print(best)
What is printed?
  1. A. 8
  2. B. 10
  3. C. 12
  4. D. 6

Correct answer: B. 10

The rectangle of height 5 and width 2 gives 10, and height 6 alone gives 6. The stack keeps increasing heights and pops when a shorter bar closes them.

More Coding Interview Problems questions

Exams that ask this topic