Data Structures & AlgorithmsHardProduct Company SDE · graph round

Problem: Check whether the directed graph with edges 0->1, 1->2, 2->0, 2->3 contains a cycle using Kahn's algorithm (count the nodes that get processed). What is printed?

Problem: Check whether the directed graph with edges 0->1, 1->2, 2->0, 2->3 contains a cycle using Kahn's algorithm (count the nodes that get processed). What is printed?
from collections import deque
n = 4
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]
g = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
    g[u].append(v)
    indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
done = 0
while q:
    u = q.popleft()
    done += 1
    for v in g[u]:
        indeg[v] -= 1
        if indeg[v] == 0:
            q.append(v)
print('cycle' if done < n else 'acyclic')
What is printed?
  1. A. acyclic
  2. B. 3
  3. C. cycle
  4. D. 4

Correct answer: C. cycle

Vertices 0, 1 and 2 form a directed cycle, so none of them ever reaches in-degree zero and done stays below 4, which the code reports as a cycle.

More Coding Interview Problems questions

Exams that ask this topic