Problem Link - Count Connected Components
Problem Statement:
You are given N nodes and M connections. The task is to determine the total number of connected components in the graph formed by these nodes and connections. Each connected component has a unique leader, and thus the number of leaders will be equal to the number of connected components.
Approach:
This solution employs the Disjoint Set Union (DSU), or Union-Find, to efficiently manage connected components.
-
Initialization: Two arrays are used:
-
parent[]
: Tracks the parent of each node, initialized so each node is its own parent. -
setSize[]
: Stores the size of each component, initialized to1
.
-
-
Finding Leaders: The function
dsuFind(int a)
finds the leader of the component containing nodea
. Ifa
is its own parent, it is the leader; otherwise, it recursively finds the leader with path compression. -
Union of Components: The function
dsuUnion(int a, int b)
connects two nodes by merging their components. It attaches the smaller component to the larger to maintain balance. -
Counting Connected Components: After processing connections, the program counts unique leaders by checking how many nodes are their own parents.
Time Complexity:
-
Union and Find Operations: Amortized O(α(N)), where
α
is the inverse Ackermann function, making these operations nearly constant. -
Counting Leaders: O(N), for a single pass through the nodes.
Space Complexity:
- O(N) for the
parent
andsetSize
arrays that store node information.