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?- A. True True
- B. False True
- C. False False
- 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
- Problem: Find the shortest travel time from node 0 to every node in a road network with non-negative weights. python import heapq def…
- Problem: A network has V = 10⁵ routers and E = 2 × 10⁵ links with latencies that can be negative (but no negative cycle). Which…
- Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions? python…
- Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm. python def kruskal(n…
- Problem: Find the length of the shortest transformation from a start word to an end word, changing one letter at a time, every…
- Problem: Determine whether a graph can be coloured with two colours so that no edge joins equal colours (bipartite). python from…