Data Structures & AlgorithmsModerateCodeforces Div2 B · combinatorics

Problem: The number of structurally distinct binary search trees on 5 keys is the Catalan number. What does this code print?

Problem: The number of structurally distinct binary search trees on 5 keys is the Catalan number. What does this code print?
dp = [1] + [0] * 5
for n in range(1, 6):
    dp[n] = sum(dp[i] * dp[n - 1 - i] for i in range(n))
print(dp[5])
What is printed?
  1. A. 32
  2. B. 52
  3. C. 42
  4. D. 30

Correct answer: C. 42

dp[n] = sum over root choices of left-size times right-size, which is the Catalan recurrence. C(5) = 42, while 32 = 2^5 is the trap of counting subsets.

More Coding Interview Problems questions

Exams that ask this topic