Union Find Data Structure
The Union Find data structure has mainly 3 operations: - MakeUnionFind() - set up singleton components - find() - find the component that contains element - union() - merge two components and
Basic Setup (or Notations)
Let us consider a set partitioned into the components with only a single element i.e., each belongs to a single component
Implementation
Naive Implementation
- Let us assume
-
Create a dictionary
component
-
Now for the function
MakeUnionFind(S)
- Setcomponent[i] = i
for each -
For the function
find(i)
- returncomponent[i]
- And for the function
union(i, j)
- set all the from the component to
A better Implementation
As we saw above, the union
function was inefficient.
So to improve that, we could create two more dictionaries members
and sizes
, where members[c] = list of all members of the component c
and sizes[c] = len(members[c])
Time Complexity
Basic Implementation
The time complexity of the funtions are:
- MakeUnionFind
-
- find(i)
-
- union(i,j)
-
A Better Implementation
The time complexity of the funtions are:
- MakeUnionFind
-
- find(i)
-
- union(i,j)
-
- Average Cost of union
operations -