Problem Link - Naive DSU Implementation
Problem Statement -
Implement the dsuFind and dsuUnion functions of DSU in the code editor.
Approach:
The key idea of this code is to utilize the Disjoint Set Union (DSU) or Union-Find data structure to efficiently handle a collection of disjoint (non-overlapping) sets. This structure supports two main operations:
dsuFind(int a)
:
-
If
parent[a]
equalsa
, it means thata
is the leader of its set. Thus, the function returnsa
. -
If
parent[a]
does not equala
, the function recursively calls itself withparent[a]
until it finds the leader. This implements the path compression technique, making future queries faster by directly linking elements to their set leader.
dsuUnion(int a, int b)
:
-
It first finds the leaders of both
a
andb
by callingdsuFind
on both. -
If the leaders are different, it updates the parent of
leader_b
to beleader_a
, effectively merging the two sets. -
This operation ensures that all elements of one set now point to the leader of the other set.
Time Complexity:
-
dsuFind: O(α(n)), where
α
is the inverse Ackermann function. This function grows very slowly, so it is nearly constant time for practical purposes. -
dsuUnion: O(α(n)), for the same reasons as above.
Space Complexity:
- O(n) for storing the parent array, where n is the number of elements.