Design an algorithm to detect a cycle in a directed graph.

Instruction: Outline an approach for detecting cycles in directed graphs and discuss its time complexity.

Context: Candidates will demonstrate their knowledge of graph theory and their ability to design efficient algorithms for cycle detection, a common problem in software development involving directed graphs.

Updated

Official answer

Kahn's topological-removal algorithm detects cycles without recursion. Include every vertex, even one that appears only as an edge target:

from collections import deque

def has_directed_cycle(graph):
    indegree = {u: 0 for u in graph}
    for neighbors in graph.values():
        for v in neighbors:
            indegree[v] = indegree.get(v, 0) + 1
    queue = deque(u for u, degree in indegree.items() if degree == 0)
    removed = 0
    while queue:
        u = queue.popleft()
        removed += 1
        for v in graph.get(u, ()):
            indegree[v] -= 1
            if indegree[v] == 0:
                queue.append(v)
    return removed != len(indegree)

Assume a finite adjacency mapping with reusable neighbor sequences and hashable vertices. The algorithm removes zero-indegree vertices and their outgoing edges. If any vertices remain, they contain or depend on a directed cycle; returning True detects its existence, not every cycle member. Time is O(V+E), with O(V) auxiliary space under standard map operations.

A DFS alternative uses white/unvisited, gray/on-current-path and black/completed states. An edge to gray detects a cycle; an edge to any visited node is not enough. Start DFS from every unvisited vertex to cover disconnected components. Test self-loops, a disconnected cycle, a diamond DAG, duplicate edges and empty input.

Related Questions