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)
  1. A. [5, 4, 2, 3, 1, 0]
  2. B. [4, 5, 2, 0, 3, 1]
  3. C. [4, 5, 0, 2, 3, 1]
  4. 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).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic