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?- A. 5 42 1
- B. 6 42 1
- C. 5 120 1
- 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
- Problem: Count the number of ways to tile a 2 × n board with 2 × 1 dominoes, modulo 10⁹ + 7. cpp const long long MOD = 1e9 + 7; long long…
- Problem: Find the minimum number of perfect squares that sum to n. python def squares(n): dp = [0] + [float('inf')] n for i in range(1, n…
- Problem: Count the number of distinct subsequences of s that equal t. python def distinct(s, t): dp = [1] + [0] len(t) for ch in s: for j…
- Problem: Find the longest increasing path in a matrix (moving up/down/left/right to strictly larger values). python from functools import…
- Problem: Find the cheapest way to cut a stick of length n at given positions; each cut costs the current piece's length. python from…
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right with its current neighbours (1 beyond the ends). Maximise coins…