- Published on
leetcode-323 Number of Connected Components in Undirected Graph
- Authors

- Name
- Gene Zhang
[323] Number of Connected Components
Key Concept: Union-Find or DFS - Use union-find to efficiently count connected components by merging nodes.
# Given n nodes and list of edges, return number of connected components.
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
parent = list(range(n))
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(x, y):
root_x, root_y = find(x), find(y)
if root_x != root_y:
parent[root_x] = root_y
return True
return False
components = n
for x, y in edges:
if union(x, y):
components -= 1
return components
# Time: O(E * α(N)), Space: O(N)
# AirBnB: Tests union-find understanding