PracticeNeetCode ↗LeetCode ↗
Given n nodes labeled 0 to n - 1 and a list of undirected edges, return the number of connected components in the graph.
find calls close to O(1) amortized as unions accumulate.parent array where every node starts as its own parent (n separate components).(a, b), find the roots of a and b; if they differ, union them (this reduces the component count by one).find so lookups stay fast.n.Time: O(V + E · α(V)) (α is the inverse Ackermann function, effectively constant) — Space: O(V)
def countComponents(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]]
x = parent[x]
return x
def union(a: int, b: int) -> bool:
root_a, root_b = find(a), find(b)
if root_a == root_b:
return False
parent[root_a] = root_b
return True
components = n
for a, b in edges:
if union(a, b):
components -= 1
return componentsHow the solution above works, piece by piece.
parent[x] points toward the representative (root) of x's group. Initially every node is its own group, so there are n components.find follows parent links to the root, and path halving (parent[x] = parent[parent[x]]) shortens the chain as it goes.union(a, b) joins two groups by pointing one root at the other; it returns False if they were already in the same group.components -= 1.Running it on n = 5, edges = [[0, 1], [1, 2], [3, 4]]:
parent (index = node). Each union points one root at another. After the three edges, the roots are 2 (for 0, 1, 2) and 4 (for 3, 4): 2 components.