The Number of Connected Components in an Undirected Graph problem gives you n nodes labeled 0 to n-1 and a list of undirected edges. Find the number of connected components — groups of nodes where every node is reachable from every other node in the group. This is a foundational graph connectivity problem solvable with DFS, BFS, or Union-Find.
Apple, Twitter, Meta, Amazon, LinkedIn, TikTok, and Google ask this as the standard graph connectivity problem. It tests knowledge of Union-Find vs DFS/BFS approaches and their trade-offs. The union find, BFS, graph, and DFS interview pattern is at the core, and it's frequently asked as a building block before harder graph problems.
Union-Find (most efficient). Initialize each node as its own component (n components). For each edge (u, v), union the two nodes. If they were in different components, decrement the component count. Return the final count.
DFS alternative: Mark nodes as visited, do DFS from each unvisited node, each DFS invocation = one component.
n=5, edges=[(0,1),(1,2),(3,4)].
Connected components is one of the most reused graph primitives. Master both Union-Find (great for dynamic edge additions) and DFS (simpler to implement for static graphs). For interviews, Union-Find with path compression and union-by-rank is the cleanest and most impressive. Practice this as a sub-problem: it appears inside Minimum Spanning Tree, graph coloring, and network connectivity problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Graph Valid Tree | Medium | Solve | |
| Is Graph Bipartite? | Medium | Solve | |
| Redundant Connection | Medium | Solve | |
| Possible Bipartition | Medium | Solve | |
| Count the Number of Complete Components | Medium | Solve |