Graph Cycle Detection | Data Structures Interview | Skill-Lync Resources
Medium Data Structures Graphs

How do you detect a cycle in a directed graph?

Answer

Use DFS with three states: unvisited, visiting (in current path), and visited. For each node, mark as visiting, recurse on neighbors; if you encounter a visiting node, there's a cycle. After processing all neighbors, mark as visited. Alternative: Kahn's topological sort - if not all nodes are processed (remaining nodes have cycles), a cycle exists. Both are O(V+E). For undirected graphs, track parent during DFS.

Master These Concepts with IIT Certification
IIT Certified

Master These Concepts with IIT Certification

175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.

Relevant for Roles

Software Engineer Backend Developer Algorithm Developer