Workspace Union Find Template
0d
DSA Cheat Sheets

Union-find root lookup

Find a representative using path halving.

Rootparent[x] = xInitialize each node as its own root
UnionAttach smaller rootUpdate size only on surviving root

Python

def find(p,x):
    while p[x]!=x:
        p[x]=p[p[x]]
        x=p[x]
    return x

C++

int find(std::vector<int>& p,int x){while(p[x]!=x){p[x]=p[p[x]];x=p[x];}return x;}

Java

static int find(int[] p,int x){while(p[x]!=x){p[x]=p[p[x]];x=p[x];}return x;}