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))- A. 7 3 2
- B. 6 3 2
- C. 6 2 2
- 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.
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? (longest path in a DAG using topological order) python g = {'A': [('B', 3), ('C', 2)], 'B': [('D', 4)], 'C': [('D', 1)…
- What is printed? (unique paths count with memoised recursion vs closed form) python from functools import lrucache from math import comb…
- What is printed? (LIS length with O(n²) DP and the number of LIS) python a = [1, 3, 5, 4, 7] n = len(a); L = [1] n; C = [1] n for i in…
- What is printed? (coin change: number of combinations) python def ways(coins, amt): dp = [1] + [0] amt for c in coins: for a in range(c…
- What is printed? (rod cutting – maximise revenue) python price = [0, 1, 5, 8, 9, 10, 17, 17, 20] n = 8; r = [0] (n + 1) for j in range(1…
- What is printed? (subset sum with a boolean DP table) python a = [3, 34, 4, 12, 5, 2] def can(t): dp = [True] + [False] t for x in a: for…