I was solving this question on CodeChef and going through the editorial.
Here's the pseudo-code for the implemented disjoint-set algorithm :
Initialize parent[i] = i
Let S[i] denote the initial array.
int find(int i)
int j
if(parent[i]==i)
return i
else
j=find(parent[i])
//Path Compression Heuristics
parent[i]=j
return j
set_union(int i,int j)
int x1,y1
x1=find(i)
y1=find(j)
//parent of both of them will be the one with the highest score
if(S[x1]>S[y1])
parent[y1]=x1
else if ( S[x1] < S[y1])
parent[x1]=y1
solve()
if(query == 0)
Input x and y
px = find(x)
py = find(y)
if(px == py)
print "Invalid query!"
else
set_union(px,py)
else
Input x.
print find(x)
What is the time complexity of union
and find
?
IMO, the time complexity of find
is O(depth)
, so in worst case, if I am not using path-comression, the complexity turns out to be O(n). Since union
also uses find
, it also has the complexity of O(n). If instead we throw out the find
from union
and instead pass the parents of two sets to union
, complexity of union
is O(1). Please correct me, if I am wrong.
If path compression is applied, then what is the time complexity?