Data Structures & AlgorithmsModerateCognizant · Capgemini pattern
Kahn's topological sort with a FIFO queue (initial zero-indegree vertices in increasing order). What is printed?
Kahn's topological sort with a FIFO queue (initial zero-indegree vertices in increasing order). What is printed?
from collections import deque
g = {5: [2, 0], 4: [0, 1], 2: [3], 3: [1], 0: [], 1: []}
indeg = {v: 0 for v in g}
for u in g:
for v in g[u]: indeg[v] += 1
q = deque(sorted(v for v in g if indeg[v] == 0)); out = []
while q:
u = q.popleft(); out.append(u)
for v in g[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
print(out)- A. [5, 4, 2, 3, 1, 0]
- B. [4, 5, 2, 0, 3, 1]
- C. [4, 5, 0, 2, 3, 1]
- D. [5, 4, 0, 2, 3, 1]
Correct answer: B. [4, 5, 2, 0, 3, 1]
Start with 4 and 5. Popping 4 lowers 0 and 1 (0 still waits for 5). Popping 5 frees 2 and then 0 (in adjacency order 2, 0). Then 2 frees 3, 0 frees nothing, 3 frees 1. A DFS-based topological sort would give a different but also valid order. O(V + E).
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
- Kruskal's algorithm: which edges are accepted, in order, for the graph below? python edges = sorted([(7, 'A', 'B'), (5, 'A', 'D'), (8…
- How many times is the base case reached when computing C(5, 2) with the plain recursion C(n, k) = C(n−1, k−1) + C(n−1, k)? python base = 0…
- What is printed? (Tower of Hanoi: number of moves and the 5th move) python moves = [] def hanoi(n, a, b, c): if n == 0: return hanoi(n…
- What is printed? (recursion output order) python out = [] def f(n): if n == 0: return out.append(n) f(n - 1) out.append(n) f(3) print(out)
- Solve the recurrences numerically: how many 'work units' does each do for n = 64? python from functools import lrucache @lrucache(None)…
- 0/1 knapsack, capacity 50: items (weight, value) = (10, 60), (20, 100), (30, 120). What do greedy-by-ratio and DP give? python items =…