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))- A. 14 4 8
- B. 14 3 8
- C. 24 3 8
- 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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (diameter of an unweighted tree with two BFS passes) python from collections import deque edges = [(1, 2), (1, 3), (2…
- What is printed? (articulation points by brute force removal) python edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (5…
- What is printed? (strongly connected components count, Kosaraju) python g = {0: [1], 1: [2], 2: [0, 3], 3: [4], 4: [5], 5: [3], 6: [5, 7]…
- What is printed? (greedy fractional knapsack) python items = [(10, 60), (20, 100), (30, 120)] # (weight, value) cap, total = 50, 0.0 for…
- What is printed? (minimum platforms / overlapping intervals with a heap) python import heapq iv = sorted([(1, 4), (2, 3), (3, 6), (5, 7)…
- A complete binary tree is stored in an array with the root at index 1. A node at index 37 – what are its parent, left child and right…