Data Structures & AlgorithmsVery hardProduct company OA

Largest rectangle under a histogram using a stack of (start index, height). What is printed?

Largest rectangle under a histogram using a stack of (start index, height). What is printed?
def rect(h):
    st, best = [], 0
    for i, x in enumerate(h + [0]):
        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))
    return best
print(rect([2, 4, 4, 1, 5, 6, 2, 3]), rect([3, 3, 3, 3]), rect([1, 2, 3, 4, 5]))
  1. A. 12 12 15
  2. B. 10 12 9
  3. C. 10 16 9
  4. D. 8 12 9

Correct answer: B. 10 12 9

When a bar is popped, the current index is the first bar to its right that is lower, and the stored start already extends left over all taller bars it replaced, so its rectangle is height × (i − start). The sentinel 0 flushes the stack. [2,4,4,1,5,6,2,3]: best is 5 × 2 = 10 (bars 5, 6); 4 × 2 = 8, 1 × 8 = 8, 2 × 4 = 8. [3,3,3,3]: 12. [1,2,3,4,5]: 3 × 3 = 9. The answer 15 adds the bars instead of taking the minimum height. O(n) total.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic