1.Implementation of union find

Implementing union and find

Union Find : ( O(n) )

int findParent(vector<int> v, int node)
{
    while (v[node] != -1)
    {
        node = v[node];
    }
    return node;
}

void uni(vector<int> &v, vector<int> &sz, int a, int b)
{

    int parA = findParent(v, a);
    int parB = findParent(v, b);

    if (parA != parB)
    {
        v[parA] = parB;
        sz[parB] = sz[parB] + sz[parA];
    }
    return;
}

Union using rank and Find using path compression : (O (log (n) ))

Last updated

Was this helpful?