Algo-Sim › Advanced Graphs

Number of Connected Components (Union-Find)

Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input

Count the pieces of an undirected graph with union-find: start with n sets and subtract one for every edge that joins two of them.

Problem

Given n nodes labelled 0..n − 1 and a list of undirected edges, return the number of connected components: groups of nodes that are joined to each other by paths and to nothing else. Here the edges are processed one at a time, as if they arrived in a stream.

Constraints

Edge cases to test

Follow-up questions

Why path compression and union by rank?
Together they make each operation O(α(n)), effectively constant.
When is union-find better than DFS?
When edges arrive online, or when you only need to know whether two nodes are connected.

Solution

Java

public int countComponents(int n, int[][] edges) {
    int[] parent = new int[n];
    for (int i = 0; i < n; i++) parent[i] = i;
    int components = n;
    for (int[] e : edges) {
        int a = find(parent, e[0]), b = find(parent, e[1]);
        if (a != b) {
            parent[a] = b;
            components--;
        }
    }
    return components;
}

private int find(int[] parent, int x) {
    while (parent[x] != x) {
        parent[x] = parent[parent[x]];
        x = parent[x];
    }
    return x;
}

Python

def count_components(n, edges):
    parent = list(range(n))
    components = n
    for u, v in edges:
        a, b = find(parent, u), find(parent, v)
        if a != b:
            parent[a] = b
            components -= 1
    return components


def find(parent, x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int countComponents(int n, vector<vector<int>> &edges) {
        vector<int> parent = vector<int>(n);
        for (int i = 0; i < n; i++)
            parent[i] = i;
        int components = n;
        for (vector<int> &e : edges) {
            int a = find(parent, e[0]), b = find(parent, e[1]);
            if (a != b) {
                parent[a] = b;
                components--;
            }
        }
        return components;
    }

    int find(vector<int> &parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }
};

More Advanced Graphs problems