1. Understand the Goal: The user wants an algorithm to detect cycles in a directed graph.
-
Identify Key Concepts:
- Graph: A set of vertices (nodes) and edges.
- Directed Graph: Edges have a direction (from u to v). u→v is not the same as v→u.
- Cycle: A path that starts and ends at the same vertex (e.g., A→B→C→A).
- Algorithms: Common approaches include Depth First Search (DFS) and Topological Sort (Kahn's Algorithm).
-
Select the Approaches:
- Approach 1: Depth First Search (DFS) with Recursion Stack. This is the most standard and intuitive method for cycle detection.
- Approach 2: Topological Sort (Kahn's Algorithm). This works by removing nodes with in-degree 0. If any nodes remain, there's a cycle.
-
Draft Approach 1 (DFS - "Three Colors" method):
- Concept: Keep track of the state of each node: Unvisited, Visiting (in the current recursion stack), and Visited.
- Logic:
- Mark node as "Visiting".
- For each neighbor:
- If neighbor is "Visiting", we found a back edge → Cycle Detected.
- If neighbor is "Unvisited", recurse.
- Mark node as "Visited".
- Time Complexity: O(V+E).
- Space Complexity: O(V).
-
Draft Approach 2 (Kahn's Algorithm - Topological Sort):
- Concept: Calculate in-degrees. Nodes with in-degree 0 can start a topological order. Remove them, update in-degrees of neighbors.
- Logic:
- Calculate in-degree for all nodes.
- Push all nodes with in-degree 0 to a queue.
- While queue is not empty:
- Pop node u.
- For each neighbor v of u:
- Decrement in-degree of v.
- If in-degree of v becomes 0, push to queue.
-
Structure the Answer:
- Introduction: Briefly explain what a cycle is in a directed graph.
- Method 1: DFS (Depth First Search): This is usually the preferred "interview" answer.
- Explain the logic (Visited vs. Recursion Stack).
- Provide the Algorithm steps.
- Provide Pseudocode.
- Analyze Complexity.
- Method 2: Topological Sort (Kahn's Algorithm): Good alternative, especially if you already need a topological sort.
- Explain the logic (Indegrees).
- Provide Algorithm steps.
- Analyze Complexity.
- Example: A small visual example helps cement understanding.
-
Refining the DFS Explanation:
- It's crucial to distinguish between "visited globally" and "visited in the current path". If I just use a standard
visited array, I might flag A→B→C and A→D→B as a cycle (which is wrong, just two paths merging). I need recursion_stack or "colors".
- Let's use the "colors" terminology (White/Gray/Black) or simply distinct arrays
visited and recStack. recStack is often clearer for implementation details.
-
Refining the Kahn's Explanation:
- Emphasize why it works: A cycle prevents any node inside it from ever reaching in-degree 0.
-
Writing the Content (Mental Draft & Polish):
- DFS Code: Need a
hasCycle function. Loop through all nodes (to handle disconnected graphs). Call dfs. Inside dfs: mark current recStack = true. Check neighbors. If neighbor in recStack, return true. Backtrack: set recStack = false.
- Kahn's Code: Queue logic. Count processed nodes.
-
Final Review: Does this directly answer the prompt? Yes. Is it clear? Yes. Are the complexities correct? Yes.
(Self-Correction during drafting): I should probably present DFS as the primary solution because it's more general-purpose for cycle detection, while Kahn's is specific to DAGs (Directed Acyclic Graphs). I will present DFS first.
Let's write out the response based on this structure.
- Introduction: Directed graph cycle detection is fundamental.
- Algorithm 1 (DFS): Use two boolean arrays:
visited and recursion_stack.
visited: Keep track of nodes seen to avoid reprocessing.
recursion_stack: Keep track of nodes in the current path.
- If we encounter a node that is in the
recursion_stack, we have found a back edge → Cycle.
- Algorithm 2 (Kahn's): Topological sort.
- If we can't sort all nodes, there is a cycle.
I will provide Python-like pseudocode for clarity.
Here are the two most common algorithms for detecting cycles in a directed graph: Depth First Search (DFS) and Kahn's Algorithm (Topological Sort).
Approach 1: DFS with Recursion Stack (The "Colors" Method)
This is generally the preferred method for general cycle detection. It works by tracking the state of nodes during the traversal.
The Logic:
Every node is in one of three states:
- White (Unvisited): The node has not been processed yet.
- Gray (Visiting/Recursion Stack): The node is currently being processed (the DFS has entered it but hasn't finished exploring all its descendants). If we encounter another "Gray" node, we have found a back edge, which indicates a cycle.
- Black (Visited): The node and all its descendants have been fully processed.
Algorithm Steps:
- Initialize all nodes as "Unvisited."
- Iterate through every node in the graph. If a node is "Unvisited," start a DFS from it.
- Inside the DFS function:
- Mark the current node as "Visiting."
- For every neighbor of the current node:
- If the neighbor is "Visiting," a cycle exists. Return
True.
- If the neighbor is "Unvisited," recurse on that neighbor. If the recursive call returns
True, propagate True up the stack.
- After checking all neighbors, mark the current node as "Visited."
- Return
False (no cycle found starting from this specific path).
Pseudocode:
function hasCycle(graph):
visited = {} // Dictionary to store state: "visiting" or "visited"
for node in graph:
visited[node] = "unvisited"
for node in graph:
if visited[node] == "unvisited":
if dfs(node, visited):
return True
return False
function dfs(node, visited):
visited[node] = "visiting"
for neighbor in graph[node]:
if visited[neighbor] == "visiting":
return True // Back edge found!
if visited[neighbor] == "unvisited":
if dfs(neighbor, visited):
return True
visited[node] = "visited"
return False
Time Complexity: O(V+E) (Vertex + Edge)
Space Complexity: O(V) (For the visited map and recursion stack)
Approach 2: Kahn's Algorithm (Topological Sort)
This approach is useful if you also need a topological ordering of the graph. It works by peeling away nodes that have no dependencies (in-degree 0).
The Logic:
A Directed Acyclic Graph (DAG) must have at least one node with an in-degree of 0 (no edges pointing to it). If we repeatedly remove nodes with in-degree 0, we should eventually remove all nodes. If nodes remain that cannot be removed, they form a cycle.
Algorithm Steps:
- Compute the in-degree (number of incoming edges) for every node.
- Initialize a queue with all nodes that have an in-degree of 0.
- Initialize a counter
visited_count = 0.
- While the queue is not empty:
- Dequeue a node.
- Increment
visited_count.
- For every neighbor of this node, decrement their in-degree.
- If a neighbor's in-degree becomes 0, add it to the queue.
- After the loop, if
visited_count equals the total number of nodes, there is no cycle. Otherwise, a cycle exists.
Pseudocode:
function hasCycleKahn(graph, numNodes):
in_degree = array of size numNodes initialized to 0
queue = empty queue
// 1. Calculate in-degrees
for node in graph:
for neighbor in graph[node]:
in_degree[neighbor]++
// 2. Add nodes with 0 in-degree to queue
for i from 0 to numNodes - 1:
if in_degree[i] == 0:
queue.enqueue(i)
count = 0
// 3. Process queue
while queue is not empty:
current = queue.dequeue()
count++
for neighbor in graph[current]:
in_degree[neighbor]--
if in_degree[neighbor] == 0:
queue.enqueue(neighbor)
// 4. Check if we processed all nodes
if count == numNodes:
return False // No cycle
else:
return True // Cycle exists
Time Complexity: O(V+E)
Space Complexity: O(V)
Summary
- Use DFS if you simply need a boolean answer (Yes/No) or need to find the specific path of the cycle.
- Use Kahn's Algorithm if you need to perform a Topological Sort or want an iterative solution without recursion depth limits.