Detect a cycle in an undirected graph

Pattern: Cycle detection

medium

Process the edges one by one with union-find. If an edge's two ends are already in the same group, there was already a path between them, so this edge closes a cycle.

The problem

Return whether an undirected graph contains a cycle. Vertices are numbered from 0 and each edge is given as [u, v].

Think first

  • When does adding an edge create a cycle?
  • Which structure answers 'already connected?' quickly?
  • Does the graph need to be connected?

Hints

    Brute force, and why it fails

    DFS from every vertex, remembering the parent, and look for an edge to a visited non-parent: also O(V + E).

    The key insight

    An edge between two vertices of the same group is exactly a cycle, so one pass of union-find decides it.

    Dry run

    n = 5, edges 0-1, 1-2, 2-3, 3-4, 4-1. Join 0-1, 1-2, 2-3, 3-4: all in one group.

    Step 1 of 3

    The plan

    for (u, v): if find(u) == find(v): return true; union(u, v)
    return false
    

    Complexity

    Time
    O(V + E α(V))
    Space
    O(V)

    Almost constant time per edge.

    Edge cases

    • A single vertex with no edges.
    • A graph in several pieces.
    • A self-loop or repeated edge, if the problem allows it.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isCycle(int n, int[][] edges) {
            int[] parent = new int[n];
            for (int i = 0; i < n; i++) parent[i] = i;
            for (int[] e : edges) {
                int a = find(parent, e[0]), b = find(parent, e[1]);
                if (a == b) return true;            // already connected: this edge closes a loop
                parent[a] = b;
            }
            return false;
        }
    
        private int find(int[] parent, int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    }

    C++

    class Solution {
    public:
        bool isCycle(int n, vector<vector<int>>& edges) {
            vector<int> parent(n);
            for (int i = 0; i < n; i++) parent[i] = i;
            for (const vector<int>& e : edges) {
                int a = find(parent, e[0]), b = find(parent, e[1]);
                if (a == b) return true;            // already connected: this edge closes a loop
                parent[a] = b;
            }
            return false;
        }
    
        int find(vector<int>& parent, int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    };

    Python

    class Solution:
        def isCycle(self, n: int, edges: list[list[int]]) -> bool:
            parent = list(range(n))
    
            def find(x):
                while parent[x] != x:
                    parent[x] = parent[parent[x]]
                    x = parent[x]
                return x
    
            for u, v in edges:
                a, b = find(u), find(v)
                if a == b:
                    return True                     # already connected: this edge closes a loop
                parent[a] = b
            return False

    Common mistakes

    • Treating the edge back to the parent as a cycle in the DFS version.
    • Using this method on directed graphs.

    Similar problems