Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count all paths from node 0 to node n − 1 in a DAG (memoised DFS).

Problem: Count all paths from node 0 to node n − 1 in a DAG (memoised DFS).
from functools import lru_cache
g = {0: [1, 2, 3], 1: [3, 4], 2: [3, 5], 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))
What is printed?
  1. A. 18
  2. B. 4
  3. C. 2
  4. D. 8

Correct answer: D. 8

paths(4) = 1, paths(3) = 2, paths(2) = 3, paths(1) = 3, so paths(0) = 3 + 3 + 2 = 8; memoisation makes it O(V + E). Returning 1 + sum counts nodes visited along the way (18), targeting node n − 2 instead of n − 1 gives 4, and counting only the shortest paths 0 → 2 → 5 and 0 → 3 → 5 gives 2.

More Coding Interview Problems questions

Exams that ask this topic