ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from collections import deque
n = 4
edges = [(0, 2), (1, 2), (2, 3), (0, 3)]
indeg = [0] * n
adj = [[] for _ in range(n)]
for u, v in edges:
    adj[u].append(v)
    indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
order = []
while q:
    u = q.popleft()
    order.append(u)
    for v in adj[u]:
        indeg[v] -= 1
        if indeg[v] == 0:
            q.append(v)
print(order)
  1. A. [0, 1, 3, 2]
  2. B. [1, 0, 2, 3]
  3. C. [0, 2, 1, 3]
  4. D. [0, 1, 2, 3]

Correct answer: D. [0, 1, 2, 3]

Kahn's algorithm starts with the in-degree-zero nodes 0 and 1 in index order. Popping 0 lowers the in-degree of 2 and 3, but 2 still waits for node 1. Popping 1 then releases 2, and then 3.

More Python Programming questions

Exams that ask this topic