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.
Connected Component Definition: A connected component is a maximal set of nodes such that there is a path between every pair of nodes in the set.
Union Find Approach:
Key Insight: Each union operation reduces the component count by 1 (when merging different components). Start with n components and track how many successful unions occur.
Time Complexity: O(E * alpha(N)) where alpha is the inverse Ackermann function (effectively O(E) for practical purposes).
n = 5, edges = [[0,1],[1,2],[3,4]]2n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]1n = 5, edges = []51 <= n <= 20000 <= edges.length <= 5000edges[i].length == 20 <= ai, bi < nai != biThere are no repeated edges.Click "Run" to execute your code against test cases
Socratic guidance - I'll ask questions, not give answers