class DSU {
public:
vector<int> parent;
vector<int> height;
vector<int> size;
DSU(int n){
parent.resize(n,-1);
size.resize(n,1); //stores size of each component. // only use when required otherwise no need
height.resize(n,1);
}
int findRoot(int node){
if(parent[node] == -1){
return node;}
return (parent[node] = findRoot(parent[node]));
}
int Union(int node1 , int node2){
int ra = findRoot(node1);
int rb = findRoot(node2);
if(ra != rb){
if(height[ra] < height[rb]){
parent[ra] = rb;
size[rb] += size[ra]; // only use when required otherwise no need
return size[rb];
}
else if(height[rb] < height[ra]){
parent[rb] = ra;
size[ra] += size[rb]; // only use when required otherwise no need
return size[ra];
}
else{
parent[rb] = ra;
height[ra] ++;
size[ra] += size[rb]; // only use when required otherwise no need
return size[ra];
}
}
return -1;
}
};Happy Learning – If you require any further information, feel free to contact me.

![[Solved] Pairing the brackets Contest Problem](https://realcoder.techss24.com/wp-content/uploads/2022/09/Solved-Pairing-the-brackets-Contest-Problem-300x200.png)
![[Solved] Friendship Test with Java, C++, Python](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Friendship-Test-with-Java-C-Python-300x200.png)
![[Solved] Series 2 with C++, Python, Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Series-2-with-C-Python-Java-300x200.png)