Data Structures & AlgorithmsModerateProduct Company SDE pattern

What is printed? (number of paths from source to target in a DAG with memoisation)

What is printed? (number of paths from source to target in a DAG with memoisation)
from functools import lru_cache
g = {0: [1, 2, 3], 1: [3, 4], 2: [4], 3: [4, 5], 4: [5], 5: []}
@lru_cache(None)
def paths(u):
    return 1 if u == 5 else sum(paths(v) for v in g[u])
print(paths(0), paths(1), paths(3))
  1. A. 7 3 2
  2. B. 6 3 2
  3. C. 6 2 2
  4. D. 8 3 2

Correct answer: B. 6 3 2

paths(5) = 1, paths(4) = 1, paths(3) = paths(4) + paths(5) = 2, paths(2) = paths(4) = 1, paths(1) = paths(3) + paths(4) = 3, paths(0) = 3 + 1 + 2 = 6. Memoisation evaluates each vertex once – O(V + E) instead of exponential re-exploration.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic