Data Structures & AlgorithmsHardTCS NQT · Product Company OA

Problem: How many distinct paths lead from vertex 0 to vertex 3 in the DAG with edges 0->1, 0->2, 1->2, 1->3, 2->3? Run the DP over the topological order 0, 1, 2, 3.

Problem: How many distinct paths lead from vertex 0 to vertex 3 in the DAG with edges 0->1, 0->2, 1->2, 1->3, 2->3? Run the DP over the topological order 0, 1, 2, 3.
adj = {0: [1, 2], 1: [2, 3], 2: [3], 3: []}
ways = {0: 1, 1: 0, 2: 0, 3: 0}
for u in [0, 1, 2, 3]:
    for v in adj[u]:
        ways[v] += ways[u]
print(ways[3])
What is printed?
  1. A. 2
  2. B. 4
  3. C. 5
  4. D. 3

Correct answer: D. 3

Processing nodes in topological order pushes each node's path count to its successors: ways becomes 1, 1, 2, 3 for nodes 0-3, i.e. 0-1-3, 0-2-3 and 0-1-2-3. Counting only the two-edge paths gives the tempting 2 and misses the route through edge 1→2.

More Coding Interview Problems questions

Exams that ask this topic