KatInterview

323. Number of Connected Components in an Undirected Graph

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Disjoint Set Union (DSU)

This problem asks for the number of connected components in a graph, which is a classic use case for the Disjoint Set Union (DSU) or Union-Find data structure. The DSU data structure is highly efficient for tracking elements partitioned into a number of disjoint (non-overlapping) sets.

Solution

Number of Connected Components in an Undirected Graph in Python

class Solution:
    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        # parent[i] stores the parent of node i.
        parent = list(range(n))
        # size[i] stores the size of the component rooted at i.
        size = [1] * n
        # Start with n components.
        components = n
        
        # Find operation with path compression.
        def find(i: int) -> int:
            if parent[i] == i:
                return i
            # Path compression: set parent to the root.
            parent[i] = find(parent[i])
            return parent[i]

        # Union operation by size.
        def union(i: int, j: int) -> None:
            nonlocal components
            root_i = find(i)
            root_j = find(j)
            
            if root_i != root_j:
                # Union by size: attach smaller tree to the root of the larger tree.
                if size[root_i] < size[root_j]:
                    root_i, root_j = root_j, root_i
                
                parent[root_j] = root_i
                size[root_i] += size[root_j]
                # Two components are merged.
                components -= 1

        # Process all edges.
        for u, v in edges:
            union(u, v)
            
        return components

Number of Connected Components in an Undirected Graph in Java

class Solution {
    public int countComponents(int n, int[][] edges) {
        // parent[i] stores the parent of node i.
        int[] parent = new int[n];
        // size[i] stores the size of the component rooted at i.
        int[] size = new int[n];
        
        // Initially, each node is its own parent (n components).
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
        
        int components = n;
        
        // Process each edge.
        for (int[] edge : edges) {
            // If the two nodes are not already in the same component, union them.
            if (union(edge[0], edge[1], parent, size)) {
                components--;
            }
        }
        
        return components;
    }
    
    // Find operation with path compression.
    private int find(int i, int[] parent) {
        if (parent[i] == i) {
            return i;
        }
        // Path compression: set parent to the root.
        parent[i] = find(parent[i], parent);
        return parent[i];
    }
    
    // Union operation by size.
    private boolean union(int i, int j, int[] parent, int[] size) {
        int root_i = find(i, parent);
        int root_j = find(j, parent);
        
        if (root_i != root_j) {
            // Union by size: attach smaller tree to the root of the larger tree.
            if (size[root_i] < size[root_j]) {
                parent[root_i] = root_j;
                size[root_j] += size[root_i];
            } else {
                parent[root_j] = root_i;
                size[root_i] += size[root_j];
            }
            return true; // Union was successful.
        }
        
        return false; // Already in the same component.
    }
}

Number of Connected Components in an Undirected Graph in C++

class Solution {
public:
    int countComponents(int n, vector<vector<int>>& edges) {
        // parent[i] stores the parent of node i.
        vector<int> parent(n);
        // size[i] stores the size of the component rooted at i.
        vector<int> size(n, 1);
        // Initially, each node is its own parent (n components).
        for (int i = 0; i < n; ++i) {
            parent[i] = i;
        }

        int components = n;

        // Find operation with path compression.
        // Using std::function to allow for recursive lambda.
        function<int(int)> find = [&](int i) {
            if (parent[i] == i) {
                return i;
            }
            // Path compression: set parent to the root.
            return parent[i] = find(parent[i]);
        };

        // Union operation by size.
        auto unite = [&](int i, int j) {
            int root_i = find(i);
            int root_j = find(j);
            if (root_i != root_j) {
                // Union by size: attach smaller tree to the root of the larger tree.
                if (size[root_i] < size[root_j]) {
                    swap(root_i, root_j);
                }
                parent[root_j] = root_i;
                size[root_i] += size[root_j];
                components--; // Two components are merged.
            }
        };

        for (const auto& edge : edges) {
            unite(edge[0], edge[1]);
        }

        return components;
    }
};

Number of Connected Components in an Undirected Graph in TypeScript

function countComponents(n: number, edges: number[][]): number {
    // parent[i] stores the parent of node i.
    const parent: number[] = Array.from({ length: n }, (_, i) => i);
    // size[i] stores the size of the component rooted at i.
    const size: number[] = Array(n).fill(1);
    // Start with n components.
    let components = n;

    // Find operation with path compression.
    const find = (i: number): number => {
        if (parent[i] === i) {
            return i;
        }
        // Path compression: set parent to the root.
        parent[i] = find(parent[i]);
        return parent[i];
    };

    // Union operation by size.
    const union = (i: number, j: number): void => {
        const root_i = find(i);
        const root_j = find(j);
        
        if (root_i !== root_j) {
            // Union by size: attach smaller tree to the root of the larger tree.
            if (size[root_i] < size[root_j]) {
                parent[root_i] = root_j;
                size[root_j] += size[root_i];
            } else {
                parent[root_j] = root_i;
                size[root_i] += size[root_j];
            }
            // Two components are merged.
            components--;
        }
    };

    // Process all edges.
    for (const [u, v] of edges) {
        union(u, v);
    }

    return components;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.