Graphs · Pattern 3 of 14

Connected components and union-find

Count or group the separate pieces of a graph. A DFS from every unvisited node works when the graph is fixed; union-find merges groups in almost O(1) when edges arrive one at a time.

5 variations · 12 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • How many groups, provinces or islands are there?
  • Edges arrive over time and you ask "are these connected yet?"
  • Things that share a key (an email, a row, an index pair) belong together
  • Sizes of groups matter: merging, removing or adding one node

The template

Connected Components
static class DSU {
    int[] parent, size;
    int count;                                    // number of components
    DSU(int n) {
        parent = new int[n]; size = new int[n]; count = n;
        for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
    }
    int find(int x) {
        while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }   // path halving
        return x;
    }
    boolean unite(int a, int b) {
        int ra = find(a), rb = find(b);
        if (ra == rb) return false;               // already in the same component
        if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
        parent[rb] = ra;                          // hang the smaller tree under the bigger
        size[ra] += size[rb];
        count--;
        return true;
    }
}

int countComponents(int n, int[][] edges) {
    DSU d = new DSU(n);
    for (int[] e : edges) d.unite(e[0], e[1]);
    return d.count;
}

The variations

  1. 1Count the components

    Run a DFS (or union-find) from every node that has not been seen yet; each new start is a new component. Spare edges (unions that return false) can rewire the graph: you need components − 1 of them.

  2. 2Edges that arrive over time

    Union-find answers "how many groups now?" after every new edge or new land cell, without searching again. Sort friendships by time and stop at the first moment the count reaches 1.

  3. 3Union by a shared key

    Join items that share something: the same email, the same row or column, two swappable indexes, or a == b. Then each group can be treated as one: sort its letters, merge its accounts, or check every != against it.

    Worked example Accounts Merge Medium Read the solution
  4. 4Weighted edges: ratios along a path

    For a / b = 2, add the edge a → b with weight 2 and b → a with 1/2. A query x / y is the product of the weights along any path from x to y (a DFS), or −1 when they are in different components.

  5. 5Use the component sizes

    Label each component and store its size. Then ask what one change does: flipping a 0 joins the distinct neighbouring islands (add their sizes + 1), and removing an infected node saves its component only if it is the only infected node there.

Mistakes to avoid

  • Comparing parent[a] == parent[b] instead of find(a) == find(b): parents are not roots until you follow them all the way up.
  • Counting components with a DFS from node 0 only. Loop over every node and start a new search from each one not yet visited.
  • Forgetting that unite returning false means the edge closed a loop: that is exactly the spare cable in "make the network connected".
Next: BFS for the shortest path →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.