Union Find With Path Compression (Java)
Implement a Java disjoint set union find with path compression and union by rank for near constant amortized time.
Code
public class UnionFind {
int[] parent, rank; int count;
public UnionFind(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) parent[i] = i; count = n; }
public int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
public boolean union(int a, int b) { int ra = find(a), rb = find(b); if (ra == rb) return false; if (rank[ra] < rank[rb]) parent[ra] = rb; else if (rank[ra] > rank[rb]) parent[rb] = ra; else { parent[rb] = ra; rank[ra]++; } count--; return true; }
public boolean connected(int a, int b) { return find(a) == find(b); }
}How the snippet works
Union Find With Path Compression (Java) keeps everything in the class UnionFind and the functions UnionFind, find, union and connected.
Applying it
The main signature reads public UnionFind(int n)
Statements that matter
public int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
public boolean connected(int a, int b) { return find(a) == find(b); }
Interactive Tools for This Topic
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `UnionFind`, `find`, `union` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.