← All Exercises

Count Connected Components with Union-Find

intermediatejavascript~25min

Background

Union-find powers Kruskal's minimum spanning tree, network connectivity checks, and percolation analysis.

Problem

Given n nodes labelled 0 to n-1 and a list of undirected edges, return the number of connected components using a union-find data structure.

Input

An integer n and an array of [a, b] edges where 0 <= a, b < n.

Output

A single integer: the number of connected components.

Sample tests

Sample 1

Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Expected: 2

Sample 2

Input: n = 4, edges = []
Expected: 4

Sample 3

Input: n = 3, edges = [[0,1],[1,2],[2,0]]
Expected: 1

Your solution

Learning objective

Implement disjoint-set union with path compression and union by rank, and use component-count invariants.