Skip to lesson

Cycle detection

A cycle exists when following a sequence of edges leads back to an already visited vertex.

Cycle detection in undirected graphs using a parent tracker

A cycle is a path in a graph that starts and ends at the same node without repeating an edge.

In an undirected graph, every edge between u and v is bidirectional. When exploring neighbour v from vertex u, moving directly back to u is not a cycle. It is simply retracing the edge you just crossed.

Example 1 · Brute force: drop each edge and re-search, O(E * (V + E)) time, O(V + E) space

Main.javaJava
import java.util.*;
public class Main {    static boolean connected(int n, int[][] edges, int skip, int from, int to) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        for (int i = 0; i < edges.length; i++) {            if (i == skip) continue;                      // pretend this edge is removed            adj.get(edges[i][0]).add(edges[i][1]);            adj.get(edges[i][1]).add(edges[i][0]);        }        boolean[] seen = new boolean[n];        Deque<Integer> stack = new ArrayDeque<>();        stack.push(from);        seen[from] = true;        while (!stack.isEmpty()) {            int u = stack.pop();            if (u == to) return true;            for (int v : adj.get(u)) {                if (!seen[v]) { seen[v] = true; stack.push(v); }            }        }        return false;    }
    public static void main(String[] args) {        int n = 5;        int[][] edges = {{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}};        boolean cycle = false;        for (int i = 0; i < edges.length; i++) {            if (connected(n, edges, i, edges[i][0], edges[i][1])) cycle = true;        }        System.out.println("has cycle: " + cycle);    }}
Output
has cycle: true

What this code does

  • For every edge, the code removes it and searches again. If its two ends are still connected, that edge lies on a cycle.
  • Each search costs O(V + E) and runs once per edge, so the total is E * (V + E).
  • The DFS parent check finds the same cycle in a single pass.

Example 2 · Optimal: DFS with a parent, O(V + E) time, O(V) space

Main.javaJava
import java.util.*;
public class Main {    static boolean hasCycle(int n, List<List<Integer>> adj) {        boolean[] vis = new boolean[n];        for (int i = 0; i < n; i++) {            if (!vis[i]) {                if (dfs(i, -1, adj, vis)) return true;            }        }        return false;    }
    static boolean dfs(int u, int parent, List<List<Integer>> adj, boolean[] vis) {        vis[u] = true;        for (int v : adj.get(u)) {            if (!vis[v]) {                if (dfs(v, u, adj, vis)) return true;            } else if (v != parent) {                return true; // Visited and not parent => cycle            }        }        return false;    }
    public static void main(String[] args) {        int n = 3;        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        // Triangle cycle: 0-1, 1-2, 2-0        adj.get(0).addAll(Arrays.asList(1, 2));        adj.get(1).addAll(Arrays.asList(0, 2));        adj.get(2).addAll(Arrays.asList(0, 1));
        System.out.println("Contains cycle: " + hasCycle(n, adj));    }}
Output
Contains cycle: true

What this code does

  • parent parameter prevents false cycles from bidirectional edge backtracking.
  • Reaching vertex 0 from vertex 2 when parent is 1 detects a cycle.
  • Algorithm terminates early returning true as soon as a cycle is found.
  • It is faster because one traversal sees every edge once, so no edge needs its own separate search.

To distinguish trivial backtracks from real cycles, track the parent vertex during traversal. When visiting vertex u, pass its caller parent into the DFS function. For each neighbour v of u, if v is unvisited, recurse with parent set to u. If v is already visited and v != parent, a real cycle exists. An outer loop over all vertices 0 to V - 1 handles disconnected graphs. This detects cycles across all components in O(V + E) time and O(V) space.

Cycle detection in directed graphs using three-colour DFS

In a directed graph, parent tracking is not enough. A cycle exists only when an edge points back to a vertex on the current recursion path, called a back edge.

Example 3 · Directed Graph Cycle Detection Using 3-Colour Scheme

Main.javaJava
import java.util.*;
public class Main {    static final int WHITE = 0; // Unvisited    static final int GRAY = 1;  // In active recursion call stack    static final int BLACK = 2; // Finished
    static boolean hasCycleDirected(int n, List<List<Integer>> adj) {        int[] color = new int[n];        for (int i = 0; i < n; i++) {            if (color[i] == WHITE) {                if (dfs(i, adj, color)) return true;            }        }        return false;    }
    static boolean dfs(int u, List<List<Integer>> adj, int[] color) {        color[u] = GRAY;        for (int v : adj.get(u)) {            if (color[v] == GRAY) return true; // Back edge detected            if (color[v] == WHITE) {                if (dfs(v, adj, color)) return true;            }        }        color[u] = BLACK;        return false;    }
    public static void main(String[] args) {        int n = 3;        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        // Directed cycle: 0 -> 1 -> 2 -> 0        adj.get(0).add(1);        adj.get(1).add(2);        adj.get(2).add(0);
        System.out.println("Directed cycle: " + hasCycleDirected(n, adj));    }}
Output
Directed cycle: true

What this code does

  • Vertex colour is set to GRAY upon entering the recursive call.
  • Encountering GRAY neighbour 0 from node 2 confirms a back edge.
  • Fully explored vertices turn BLACK, ensuring each node is processed once.

Use three colours: WHITE (0) unvisited, GRAY (1) on the active call path, BLACK (2) fully explored. Meeting a GRAY neighbour is a back edge, so there is a cycle. A vertex seen in an earlier branch (BLACK) is not a cycle.

When a vertex has explored all its outgoing edges, colour it BLACK. The check runs in O(V + E) time.

Circular dependencies and real-world deadlocks

Build systems like Gradle and Maven compile projects by modeling dependencies as directed graphs. A package dependency cycle between module A and module B prevents determining a valid build order. Cycle detection identifies these fatal circular dependencies before compiling.

Example 4 · Detecting Circular Package Dependencies

Main.javaJava
import java.util.*;
public class Main {    static boolean isCircularDependency(int n, int[][] prereqs) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        for (int[] p : prereqs) {            adj.get(p[1]).add(p[0]); // p[1] must build before p[0]        }
        int[] state = new int[n];        for (int i = 0; i < n; i++) {            if (state[i] == 0 && dfs(i, adj, state)) return true;        }        return false;    }
    static boolean dfs(int u, List<List<Integer>> adj, int[] state) {        state[u] = 1; // Visiting        for (int v : adj.get(u)) {            if (state[v] == 1) return true;            if (state[v] == 0 && dfs(v, adj, state)) return true;        }        state[u] = 2; // Visited        return false;    }
    public static void main(String[] args) {        int[][] valid = {{1, 0}, {2, 1}};        int[][] circular = {{1, 0}, {0, 1}};        System.out.println("Valid pipeline circular: " + isCircularDependency(3, valid));        System.out.println("Circular pipeline circular: " + isCircularDependency(2, circular));    }}
Output
Valid pipeline circular: false
Circular pipeline circular: true

What this code does

  • prereqs are converted into a directed dependency graph.
  • state array tracks 0 (unvisited), 1 (visiting), and 2 (visited).
  • Returns true for circular input {1, 0} and {0, 1} due to mutual dependency.

Database systems model transaction resource locks as wait-for directed graphs. If transaction T1 waits for T2 while T2 waits for T1, a deadlock cycle occurs. Deadlock detection algorithms run periodic directed cycle checks to identify and abort offending transactions.

Next step

Check your understanding

10 quick questions