Detect Cycle in a Directed Graph Easy 0 attempts
GeeksforGeeks ↗

Detect Cycle in a Directed Graph

Easy GraphBFSDFS GeeksforGeeks

Given a directed graph, detect if it contains a cycle.

Example: V=4, edges=[[0,1],[1,2],[2,3],[3,1]] → true (cycle: 1→2→3→1)

Sample Input
Sample Output
Constraints
  • 1 <= V <= 10^4
  • 0 <= E <= 10^4
Topics

DFS with Coloring

Use 3 states: WHITE (unvisited), GRAY (in current path), BLACK (done). A GRAY→GRAY edge means cycle.

function hasCycle(V, adj) {
  const color = Array(V).fill(0);
  function dfs(u) {
    color[u] = 1;
    for (const v of adj[u]) {
      if (color[v] === 1) return true;
      if (color[v] === 0 && dfs(v)) return true;
    }
    color[u] = 2;
    return false;
  }
  for (let i = 0; i < V; i++) if (color[i] === 0 && dfs(i)) return true;
  return false;
}

Time: O(V + E) | Space: O(V)

Saved in this browser only. Private to you.

JavaScript