Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Detect a cycle in a directed dependency graph with three-colour DFS.

Problem: Detect a cycle in a directed dependency graph with three-colour DFS.
def has_cycle(n, edges):
    adj = [[] for _ in range(n)]
    for u, v in edges: adj[u].append(v)
    color = [0] * n
    def dfs(u):
        color[u] = 1
        for v in adj[u]:
            if color[v] == 1 or (color[v] == 0 and dfs(v)): return True
        color[u] = 2
        return False
    return any(color[u] == 0 and dfs(u) for u in range(n))
print(has_cycle(4, [(0, 1), (0, 2), (1, 3), (2, 3)]), has_cycle(3, [(0, 1), (1, 2), (2, 1)]))
What is printed?
  1. A. True True
  2. B. False True
  3. C. False False
  4. D. True False

Correct answer: B. False True

A cycle exists only if DFS reaches a node that is still on the current path (colour 1, grey). In the diamond 0→1→3, 0→2→3, node 3 is reached twice but the second time it is already black (finished), which is not a cycle – a plain 'visited' check would wrongly say True. 1→2→1 is a real cycle. O(V + E).

More Coding Interview Problems questions

Exams that ask this topic