Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (number of BSTs vs number of binary heaps on keys 1..4)

What is printed? (number of BSTs vs number of binary heaps on keys 1..4)
from math import comb
from functools import lru_cache
@lru_cache(None)
def bst(n): return 1 if n <= 1 else sum(bst(i) * bst(n - 1 - i) for i in range(n))
def heaps(n):
    if n <= 1: return 1
    h = n.bit_length() - 1
    last = n - (2 ** h - 1)
    left = (2 ** (h - 1) - 1) + min(last, 2 ** (h - 1))
    return comb(n - 1, left) * heaps(left) * heaps(n - 1 - left)
print(bst(4), heaps(4), heaps(5))
  1. A. 14 4 8
  2. B. 14 3 8
  3. C. 24 3 8
  4. D. 14 3 6

Correct answer: B. 14 3 8

BSTs on 4 keys: Catalan(4) = 14. A max-heap on 1..4 has a fixed shape (complete tree), 4 at the root, and the left subtree of size 2 picks 2 of the remaining 3 keys: C(3, 2) = 3 heaps. For 5 keys: C(4, 3) × heaps(3) × heaps(1) = 4 × 2 = 8.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic