Number of Connected Components in an Undirected Graph Problem
Description
LeetCode Problem 323.
You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and an array edges where edges[i] = [a_i, b_i] indicates that there is an edge between a_i and b_i in the graph.
Return the number of connected components in the graph.
Example 1:

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

Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
Constraints:
1 <= n <= 20001 <= edges.length <= 5000edges[i] = [a_i, b_i]a_i != b_i- There are no repeated edges.
Solution
Approach: Union-Find
Start with every node in its own component, so there are n components. Each edge [a, b] either joins two different components into one, or connects two nodes that are already connected (it closes a cycle) and changes nothing.
A union-find structure tells the two cases apart:
find(x)follows parent links up to the root, the representative ofx's component. Path halving (parent[x] = parent[parent[x]]on the way up) keeps the trees short.- For each edge, compare
find(a)andfind(b). If they differ, link one root under the other and subtract one from the count. If they are equal, skip the edge.
After all edges, the count is the number of components. Isolated nodes that appear in no edge are counted correctly, because every node starts as its own component.
A DFS or BFS over an adjacency list works just as well: start a search from each unvisited node and count how many searches you start.
Complexity: O(n + E · α(n)) time, where E is the number of edges and α is the inverse Ackermann function (practically a constant), and O(n) extra space.
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
parent = list(range(n))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
components = n # every node starts alone
for a, b in edges:
ra, rb = find(a), find(b)
if ra != rb: # this edge joins two components
parent[ra] = rb
components -= 1
return components