Skip to problem
←

Detect Cycle in a Directed Graph

Easy 0 attempts

Given a directed graph with V vertices and adjacency list adj, determine whether it contains a directed cycle in any component. A directed cycle follows one or more edges and returns to its starting vertex.

An edge to a vertex visited along a different, completed path does not by itself imply a cycle. During DFS, an edge back to a vertex on the current active path does.

Function contract

Implement hasCycle(V, adj), where adj has V lists and adj[u] contains destinations of outgoing edges from u.

Output: true if any component contains a directed cycle, including a self-loop; otherwise false.

Example 1

Input
V = 4
adj = [[1],[2],[3],[1]]
Output
true

Explanation: Vertices 1 → 2 → 3 → 1 form a directed cycle.

Example 2

Input
V = 3
adj = [[1],[2],[]]
Output
false
Constraints
  • 1 <= V <= 10^4
  • 0 <= E <= 10^4
  • adj.length equals V; every neighbor is an integer from 0 to V - 1.
Topics

Iterative DFS with Active Frames

Track unvisited, active, and finished vertices. Each stack frame stores the next edge to examine. An edge to an active vertex closes a directed cycle.

javascript
function hasCycle(V, adj) {
  const color = Array(V).fill(0);
  for (let start = 0; start < V; start++)
    if (color[start] === 0) {
      const stack = [[start, 0]];
      color[start] = 1;
      while (stack.length) {
        const frame = stack[stack.length - 1],
          u = frame[0];
        if (frame[1] === adj[u].length) {
          color[u] = 2;
          stack.pop();
          continue;
        }
        const v = adj[u][frame[1]++];
        if (color[v] === 1) return true;
        if (color[v] === 0) {
          color[v] = 1;
          stack.push([v, 0]);
        }
      }
    }
  return false;
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript