Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (Catalan-style recursion with memo: number of ways to fully parenthesise a product of n matrices)
What is printed? (Catalan-style recursion with memo: number of ways to fully parenthesise a product of n matrices)
from functools import lru_cache
@lru_cache(None)
def ways(n):
if n <= 1: return 1
return sum(ways(k) * ways(n - k) for k in range(1, n))
print([ways(n) for n in range(1, 7)])- A. [1, 2, 5, 14, 42, 132]
- B. [1, 1, 2, 6, 24, 120]
- C. [1, 2, 3, 5, 8, 13]
- D. [1, 1, 2, 5, 14, 42]
Correct answer: D. [1, 1, 2, 5, 14, 42]
The last multiplication splits the chain into k and n − k matrices, so P(n) = Σ P(k)·P(n − k), giving Catalan(n − 1): 1, 1, 2, 5, 14, 42. This is why trying every parenthesisation is exponential and matrix-chain multiplication needs DP (O(n³)).
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
- Union–find with union by rank and full path compression. What is printed? python p = list(range(8)); rank = [0] 8 def find(x): if p[x] !=…
- 0-1 BFS on a grid: stepping into '#' costs 1 (a wall to break), stepping onto '.' or 'T' costs 0. What is the minimum number of walls to…
- How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices) python from…
- Fenwick (binary indexed) tree, 1-based, built by point additions; then a[3] += 10. What is printed (the internal array, a range sum and a…
- Segment tree for range-minimum with lazy range-add (the pending add stays at a node and is applied on the way up instead of being pushed…
- Four cities, symmetric distances; the bitmask DP (Held–Karp) is compared with the nearest-neighbour heuristic, both starting and ending at…