I wrote code in C++ which I think is correct. I verified on different IDE as well. But here it says, solution is wrong.
std::unordered_map<int, int> parent;
std::unordered_map<int, int> cnt;
int find(int x)
{
if(parent.find(x) == parent.end())
{
parent[x] = x;
}
int y = parent[x];
if(x!=y)
{
y = find(y);
parent[x] = y;
}
return y;
}
void merge(int x, int y)
{
int newCnt = count(x) + count(y);
parent[find(x)] = find(y);
cnt[find(x)] = newCnt;
}
int count(int x)
{
int y = find(x);
if(cnt.find(y) == cnt.end())
{
cnt[y] = 1;
}
return cnt[y];
}
void merge(int x, int y)
{
if (find(x) != find(y)) {
int newCnt = count(x) + count(y);
parent[find(x)] = find(y);
cnt[find(x)] = newCnt;
}
}