Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for a graph with a cycle and for an acyclic one?

Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for a graph with a cycle and for an acyclic one?
from collections import deque
def topo(n, edges):
    adj = [[] for _ in range(n)]; indeg = [0] * 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)
    return order
print(topo(5, [(0, 1), (1, 2), (2, 3), (3, 1), (0, 4)]), topo(4, [(3, 1), (2, 1), (1, 0)]))
What is printed?
  1. A. [0, 4] [2, 3, 1, 0]
  2. B. [0, 4, 1, 2, 3] [3, 2, 1, 0]
  3. C. [] [2, 3, 1, 0]
  4. D. [0, 1, 2, 3, 4] [2, 3, 1, 0]

Correct answer: A. [0, 4] [2, 3, 1, 0]

Nodes on the cycle 1 → 2 → 3 → 1 never reach in-degree 0, so they are silently missing: the order has 2 of 5 nodes. The fix is to report a cycle when len(order) < n. In the second graph both 2 and 3 start with in-degree 0 and are dequeued in index order, then 1, then 0. O(V + E).

More Coding Interview Problems questions

Exams that ask this topic