The user asks for an algorithm to detect cycles in a directed graph. I believe they'll want a concise and clear response, likely using DFS for cycle detection or perhaps Kahn's topological sort method as an alternative. I should provide pseudocode and explain the algorithm, including time complexity. I plan to focus on a DFS-based algorithm using color marking while mentioning Kahn's method as an alternative. I’ll skip starting with “Great question” and get straight to the response.Providing pseudocode for cycle detection
I’m presenting pseudocode for detecting cycles in a directed graph. The function hasCycle initializes two arrays: visited and inStack. It checks each vertex, and if it hasn’t been visited, it calls dfs. The dfs function marks the node as visited and tracks it in the recursion stack. It explores adjacent vertices to check for cycles. The time complexity is O(V + E). I’ll also succinctly mention Kahn's algorithm as an alternative with bullet points. Here’s a standard algorithm using depth-first search (DFS) to detect cycles in a directed graph.
Idea
In a directed graph, a cycle exists if during a DFS you encounter an edge to a vertex that is already in the current recursion stack (i.e., you're in the process of visiting it but haven't finished).
We track:
visited[v]: have we ever started a DFS from v?
inStack[v]: is v currently in the recursion stack?
If we find an edge u → v where v is inStack, a cycle exists.
Pseudocode
Assume graph is given as adjacency list adj[1..n].
pseudo
function hasCycle(adj, n):
visited[1..n] = {false}
inStack[1..n] = {false}
for v from 1 to n:
if not visited[v]:
if dfs(v, adj, visited, inStack):
return true
return false
function dfs(u, adj, visited, inStack):
visited[u] = true
inStack[u] = true
for each v in adj[u]:
if not visited[v]:
if dfs(v, adj, visited, inStack):
return true
else if inStack[v]:
// Found a back edge -> cycle
return true
inStack[u] = false // done exploring u
return false
Complexity
Time: O(V + E) — each vertex and edge is processed at most once.
Space: O(V) for visited, inStack, and recursion stack.
Alternative (brief): You can also detect cycles using Kahn’s algorithm (topological sort by repeatedly removing nodes with in-degree 0). If you cannot remove all vertices (i.e., some remain), the remaining part of the graph contains a cycle.