graph
union-find
You are given n nodes labeled from 0 to n - 1 and an undirected edge list edges. Return how many connected components the graph contains.
A connected component is a maximal group of nodes where every node can reach every other node in the same group by following edges.
Input / output
- Input:
n: int,edges: int[][] - Output: integer component count
Examples
n = 5,edges = [[0,1],[1,2],[3,4]]returns2.n = 5,edges = [[0,1],[1,2],[2,3],[3,4]]returns1.n = 4,edges = []returns4because every node is isolated.
Constraints
1 <= n <= 20000 <= edges.length <= 5000edges[i].length == 20 <= a, b < nanda != b- There are no duplicate edges
Target complexity
- Aim for near-linear
O(n + edges.length * α(n))time andO(n)extra space.
Hints
- Every time you connect two previously separate groups, the total number of components drops by one.
- A disjoint-set union (union-find) structure lets you merge groups without re-running a full DFS after each edge.
Follow-up If edges were streamed one by one and you needed the component count after each insertion, which approach would you prefer and why?
Examples
Example 1
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
Example 2
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
Example 3
Input: n = 4, edges = []
Output: 4
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.