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
n: int, edges: int[][]Examples
n = 5, edges = [[0,1],[1,2],[3,4]] returns 2.n = 5, edges = [[0,1],[1,2],[2,3],[3,4]] returns 1.n = 4, edges = [] returns 4 because every node is isolated.Constraints
1 <= n <= 20000 <= edges.length <= 5000edges[i].length == 20 <= a, b < n and a != bTarget complexity
O(n + edges.length * α(n)) time and O(n) extra space.Hints
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?