Number of Connected Components in an Undirected Graph - Problem
Imagine you have a network of n computers scattered across different locations. Some computers are directly connected to each other through cables, forming small groups or clusters. Your task is to determine how many separate network clusters exist.
You are given:
n- the total number of computers (labeled from 0 to n-1)edges- an array where eachedges[i] = [a, b]represents a direct cable connection between computeraand computerb
Goal: Count the number of connected components (separate network clusters) in this undirected graph.
Note: Two computers belong to the same component if there's a path of cables connecting them, either directly or through other computers.
Input & Output
example_1.py โ Basic Connected Components
$
Input:
n = 5, edges = [[0,1],[1,2],[3,4]]
โบ
Output:
2
๐ก Note:
There are 2 connected components: {0,1,2} and {3,4}. Node 0 connects to 1, and 1 connects to 2, forming one component. Nodes 3 and 4 form another component.
example_2.py โ All Separate Nodes
$
Input:
n = 5, edges = []
โบ
Output:
5
๐ก Note:
With no edges, each of the 5 nodes forms its own separate connected component: {0}, {1}, {2}, {3}, {4}.
example_3.py โ Single Large Component
$
Input:
n = 4, edges = [[0,1],[1,2],[2,3]]
โบ
Output:
1
๐ก Note:
All nodes are connected in a chain: 0-1-2-3, forming a single connected component {0,1,2,3}.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Components
Start with each node as its own separate component
2
Process Edges
For each edge, merge the components of the two connected nodes
3
Union by Rank
When merging, attach smaller tree under root of larger tree
4
Path Compression
Flatten tree paths during find operations for efficiency
5
Count Roots
The number of distinct root parents equals connected components
Key Takeaway
๐ฏ Key Insight: Union-Find efficiently maintains disjoint sets with near-constant time operations, making it perfect for connectivity problems where we need to group elements and count distinct groups.
Time & Space Complexity
Time Complexity
O(E ร ฮฑ(n))
E edges ร inverse Ackermann function (practically constant)
โ Linear Growth
Space Complexity
O(n)
Parent and rank arrays for Union-Find
โก Linearithmic Space
Constraints
- 1 โค n โค 2000
- 0 โค edges.length โค 5000
- edges[i].length == 2
- 0 โค ai โค bi < n
- ai != bi
- No duplicate edges in the input
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code