Number of Connected Components
Master this topic with zero to advance depth.
Number of Connected Components
Given nodes and a list of undirected edges, return the number of connected components.
Examples
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
Approach 1
Level I: DFS (Graph Traversal)
Intuition
Build an adjacency list. Perform DFS starting from each unvisited node. Each start represents a new component.
⏱ O(V+E)💾 O(V+E)
Detailed Dry Run
Start DFS(0): visits 1, 2. Count=1. Start DFS(3): visits 4. Count=2.
Approach 2
Level III: Union-Find (Direct)
Intuition
Start with components. For each edge, perform a union if the nodes are in different components and decrement the count.
⏱ O(V + E \cdot \alpha(V))💾 O(V)
Detailed Dry Run
n=5. [0,1]: Union count=4. [1,2]: Union count=3. [3,4]: Union count=2. Result = 2.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.