Union Find With Path Compression (Go)
Implement a Go disjoint set union find with path compression and union by rank for near constant amortized time.
Code
package main
type UnionFind struct {
parent []int
rank []int
count int
}
func newUF(n int) *UnionFind { return &UnionFind{parent: makeRange(n), rank: make([]int, n), count: n} }
func makeRange(n int) []int { r := make([]int, n); for i := range r { r[i] = i }; return r }
func (uf *UnionFind) Find(x int) int { for uf.parent[x] != x { uf.parent[x] = uf.parent[uf.parent[x]]; x = uf.parent[x] }; return x }
func (uf *UnionFind) Union(a, b int) bool {
ra, rb := uf.Find(a), uf.Find(b)
if ra == rb { return false }
if uf.rank[ra] < uf.rank[rb] { uf.parent[ra] = rb } else if uf.rank[ra] > uf.rank[rb] { uf.parent[rb] = ra } else { uf.parent[rb] = ra; uf.rank[ra]++ }
uf.count--; return true
}What the code performs
The working surface is the functions newUF, makeRange, Find and Union — everything else is wiring.
Applying it
Entry signature: func (uf *UnionFind) Find(x int) int
This is a method, not a free function — dispatch happens via a UnionFind value.
Statements that matter
func makeRange(n int) []int { r := make([]int, n); for i := range r { r[i] = i }; return r }
func newUF(n int) *UnionFind { return &UnionFind{parent: makeRange(n), rank: make([]int, n), count: n} }
func (uf *UnionFind) Union(a, b int) bool {
ra, rb := uf.Find(a), uf.Find(b)
if ra == rb { return false }
if uf.rank[ra] < uf.rank[rb] { uf.parent[ra] = rb } else if uf.rank[ra] > uf.rank[rb] { uf.parent[rb] = ra } else { uf.parent[rb] = ra; uf.rank[ra]++ }
uf.count--; return true
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.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.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `newUF`, `makeRange`, `Find` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.