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?- A. 2
- B. 4
- C. 5
- 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
- Problem: What is the smallest integer x >= 100 divisible by 13? Run the code. python print(next(x for x in range(100, 200) if x % 13 ==…
- Problem: How many distinct non-empty prefixes does the string 'banana' have? Run the code. python s = 'banana' print(len({s[:i] for i in…
- Problem: How many integers in [1, 30] are even but not divisible by 4? Run the code. python print(sum(1 for x in range(1, 31) if x % 2 ==…
- Problem: What is the total length covered by the union of the intervals [1, 3], [2, 6] and [8, 10]? Run the code. python iv = sorted([(1…
- Problem: What does this Python snippet print? def add(x, bucket=[]): bucket.append(x) return len(bucket) add(1); add(2) print(add(3))
- Problem: What does this Python snippet print? g = [[0]3]3 g[1][2] = 7 print(sum(map(sum, g)))