323. Number of Connected Components in an Undirected Graph
mediumGiven n nodes and a list of undirected edges, count the connected components. The cleanest introduction to Union-Find — and a useful warm-up before harder DSU problems like Redundant Connection or Accounts Merge.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph. Return the number of connected components in the graph.
Constraints
1 <= n <= 20001 <= edges.length <= 5000edges[i].length == 20 <= ai <= bi < nai != biThere are no repeated edges.
Examples
Example 1
n = 5, edges = [[0,1],[1,2],[3,4]]2Example 2
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]1Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Two equally good approaches: DFS/BFS from each unvisited node, or Union-Find merging endpoints of every edge.
Hint 2
DFS: walk every node; if unvisited, increment counter and DFS-mark its whole component.
Hint 3
Union-Find: initialize parent[i] = i and components = n. For each edge (a, b), if find(a) != find(b), union them and decrement components. Final components is the answer.
Solution approach
Reveal approach
Two clean approaches. DFS: build an adjacency list from edges; maintain a visited set; iterate i from 0 to n-1, and if i is unvisited, increment counter and run a DFS that marks every reachable node visited. Counter is the answer. Union-Find: initialize parent array as identity and components = n. For each edge (u, v), find the roots of u and v; if they differ, point one root at the other (with union-by-rank or path compression for amortized near-O(1)) and decrement components. Return components. The DSU version is slightly cleaner and scales to streaming-edge variants. Both are O((V + E)·alpha(V)) effectively.
Complexity
- Time
- O((V + E) * alpha(V))
- Space
- O(V)
Related patterns
- union-find
- dfs
- bfs
- graph
Related problems
- 261. Graph Valid Tree
- 200. Number of Islands
- 684. Redundant Connection
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Meta
More Graphs practice problems
- 127. Word Ladder
- 130. Surrounded Regions
- 133. Clone Graph
- 200. Number of Islands
- 207. Course Schedule
- 210. Course Schedule II
- 261. Graph Valid Tree
- 269. Alien Dictionary