Finding all cycles in a directed graph
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Tarjan's Strongly Connected Components (SCC) Algorithm
Another sophisticated method uses Tarjan's Algorithm, which finds strongly connected components (SCCs) in a directed graph. This algorithm is efficient because every cycle forms an SCC.
- Initialization: Assign a unique index to each node and keep a stack.
- DFS and Indexing: Perform a DFS. As nodes are recursively visited, they are given an index and a low-link value.
- Check SCC Formation:
- If a node has a low-link value equal to its index, it is a root node of an SCC. Pop nodes from the stack until the root node is reached, forming an SCC.
- Cycle Detection: If an SCC contains more than one node or a self-loop, it indicates a cycle.
Summary of Key Points
| Algorithm | Approach | Time Complexity | Characteristics |
| DFS-Based Cycle Detection | Recursion and Stack | $O(V + E)$ | Simple to implement. Uses extra space for recursion stack. Detects single cycles. |
| Tarjan's SCC Algorithm | DFS and Low-link Values | $O(V + E)$ | Detects all cycles efficiently. Useful for finding strongly connected components. |
Conclusion
Finding cycles in directed graphs is essential for numerous computational tasks. While the DFS-based method provides a straightforward approach to detecting individual cycles, Tarjan's strongly connected components algorithm offers a robust way to identify all cycles and complex structures within the graph. By leveraging these algorithms, developers and researchers can effectively manage dependencies, debug systems, and optimize networks.
Related reading
- Finding all cycles in an undirected graph
- Finding all disconnected subgraphs in a graph
- Finding all empty triangles
- Finding all permutations that match a set of rules
- Finding all the shortest paths between two nodes in unweighted undirected graph
- Finding all the subsets of a set
- Finding all permutations to get the given sum Coin change problem
- Finding all possible combinations of numbers to reach a given sum

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.