Number of Connected Components in an Undirected Graph
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.
Examples
Constraints
1 <= n <= 20001 <= edges.length <= 5000edges[i].length == 20 <= ai <= bi < nai != biThere are no repeated edges.
Union Find
Approach
1. Intuition: We start with `n` nodes, which means initially there are `n` disconnected components. 2. We can use the Union-Find algorithm to merge components as we iterate through the edges. 3. We initialize a `parent` array where each node is its own parent, and a `rank` array to keep the trees balanced. We also keep a `components` counter initialized to `n`. 4. For each edge `(u, v)`, we attempt to union their sets by finding their root parents. 5. If `u` and `v` have different root parents, they belong to different components. We merge these components using union by rank and decrement our `components` counter by 1. 6. If they have the same root parent, they are already in the same component, so we do nothing. 7. After processing all edges, the `components` counter will hold the final number of connected components.
Complexity Analysis
Time complexity is nearly O(V + E) as the union find operations take almost constant time. Space complexity is O(V) for the parent and rank arrays.