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?- A. 32
- B. 52
- C. 42
- 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
- Problem: What is the sum over all pairs (i < j) of the Hamming distances (number of differing bits) between the values in [1, 3, 5]? Run…
- Problem: People with weights [3, 2, 2, 1] must cross a river. A boat carries at most 2 people with total weight at most limit = 3, and…
- Problem: Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. She picks one pile per hour and eats up to k bananas from it…
- Problem: How many primes are there up to 100? Run the sieve. python n = 100 sieve = [True] (n + 1) sieve[0] = sieve[1] = False for i in…
- Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP. python s = '226' dp = [1]…
- Problem: Union-find with path compression and union by rank performs m operations on n elements in what amortised time per operation?