VOOZH about

URL: https://www.geeksforgeeks.org/dsa/detect-cycle-in-a-graph/

⇱ Detect Cycle in a Directed Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Detect Cycle in a Directed Graph

Last Updated : 4 Nov, 2025

Given a directed graph represented by its adjacency list adj[][], determine whether the graph contains a cycle/Loop or not.
A cycle is a path that starts and ends at the same vertex, following the direction of edges.

Examples:

Input: adj[][] = [[1], [2], [0, 3], []]

👁 1

Output: true
Explanation: There is a cycle 0 -> 1 -> 2 -> 0.

Input: adj[][] = [[2], [0], []]

👁 frame_3299

Output: false
Explanation: There is no cycle in the graph.

[Approach 1] Using DFS - O(V + E) Time and O(V) Space

To detect a cycle in a directed graph, we use Depth First Search (DFS). In DFS, we go as deep as possible from a starting node. If during this process, we reach a node that we’ve already visited in the same DFS path, it means we’ve gone back to an ancestor — this shows a cycle exists.
But there’s a problem: When we start DFS from one node, some nodes get marked as visited. Later, when we start DFS from another node, those visited nodes may appear again, even if there’s no cycle.
So, using only visited[] isn’t enough.

To fix this, we use two arrays:

  • visited[] - marks nodes visited at least once.
  • recStack[] - marks nodes currently in the recursion (active) path.

If during DFS we reach a node that’s already in the recStack, we’ve found a path from the current node back to one of its ancestors, forming a cycle. As soon as we finish exploring all paths from a node, we remove it from the recursion stack by marking recStack[node] = false. This ensures that only the nodes in the current DFS path are tracked.

Illustration:


Output
true

[Approach 2] Using Topological Sorting - O(V + E) Time and O(V) Space

The idea is to use Kahn’s algorithm because it works only for Directed Acyclic Graphs (DAGs). So, while performing topological sorting using Kahn’s algorithm, if we are able to include all the vertices in the topological order, it means the graph has no cycle and is a DAG.
However, if at the end there are still some vertices left (i.e., their in-degree never becomes 0), it means those vertices are part of a cycle. Hence, if we cannot get all the vertices in the topological sort, the graph must contain at least one cycle.


Output
true

Similar Article:
Detect Cycle in a direct graph using colors

Comment