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)])
  1. A. [1, 2, 5, 14, 42, 132]
  2. B. [1, 1, 2, 6, 24, 120]
  3. C. [1, 2, 3, 5, 8, 13]
  4. 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³)).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic