Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Count the distinct BST shapes that store keys 1..n.

Problem: Count the distinct BST shapes that store keys 1..n.
def shapes(n):
    dp = [1] + [0] * n
    for k in range(1, n + 1):
        dp[k] = sum(dp[r - 1] * dp[k - r] for r in range(1, k + 1))
    return dp[n]
print(shapes(3), shapes(5), shapes(0))
What is printed?
  1. A. 5 42 1
  2. B. 6 42 1
  3. C. 5 120 1
  4. D. 5 42 0

Correct answer: A. 5 42 1

Choosing root r leaves r − 1 keys on the left and k − r on the right, so dp[k] = Σ dp[r−1]·dp[k−r] – the Catalan numbers 1, 1, 2, 5, 14, 42. Permutations (3! = 6, 5! = 120) overcount because different insertion orders build the same tree. The empty tree counts as one shape. O(n²).

More Coding Interview Problems questions

Exams that ask this topic