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?- A. 18
- B. 4
- C. 2
- 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
- Problem: Rebuild a binary tree from its inorder and postorder traversals (distinct values) and print its preorder. python def prefrom(ino…
- Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method…
- Problem: Delete the nodes with given values from a binary tree and return the roots of the remaining forest, sorted. python class T: def…
- Problem: Print the boundary of a binary tree anticlockwise: root, left boundary (excluding leaves), all leaves left to right, then the…
- Problem: Convert a BST so each node's value becomes the sum of all values ≥ it (reverse inorder with a running sum); print the new…
- Problem: Count subtrees in which every node has the same value. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…