ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from collections import deque
def topo(n, edges):
    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)
    out = []
    while q:
        u = q.popleft()
        out.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return out if len(out) == n else []
print(topo(4, [(2, 0), (2, 3), (0, 1), (3, 1)]), topo(2, [(0, 1), (1, 0)]))
  1. A. [2, 0, 1, 3] []
  2. B. [2, 3, 0, 1] [0, 1]
  3. C. [2, 0, 3, 1] []
  4. D. [2, 0, 3, 1] [0, 1]

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

Kahn's algorithm takes nodes with no incoming edges first. Node 1 waits for both 0 and 3, and in the cycle 0 to 1 to 0 no node reaches in-degree zero, so the result is an empty list.

More Python Programming questions

Exams that ask this topic