Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max leaf on its right). Minimise the sum of internal nodes using a monotonic stack.

Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max leaf on its right). Minimise the sum of internal nodes using a monotonic stack.
def mct(a):
    st, res = [float('inf')], 0
    for x in a:
        while st[-1] <= x:
            mid = st.pop(); res += mid * min(st[-1], x)
        st.append(x)
    while len(st) > 2: res += st.pop() * st[-1]
    return res
print(mct([3, 5, 2, 4]))
What is printed?
  1. A. 43
  2. B. 38
  3. C. 52
  4. D. 40

Correct answer: A. 43

Greedily remove the smallest leaf first, pairing it with its smaller neighbour: 2 with 4 (8), then 3 with 5 (15), then 4 with 5 (20), total 43. The stack does this in O(n) and matches the O(n³) interval DP over all tree shapes.

More Coding Interview Problems questions

Exams that ask this topic