Use disjoint sets
Use disjoint sets
A disjoint-set structure partitions elements into non-overlapping groups. Find returns a representative of a group; Union merges two groups. Use it for incremental connectivity when edges are added. Store parent indices in a slice; each root is its own parent.
package main
import ( "fmt")
type DS struct{ parent, size []int }
func NewDS(n int) *DS { d := &DS{make([]int, n), make([]int, n)} for i := range d.parent { d.parent[i] = i d.size[i] = 1 } return d}func (d *DS) Find(x int) int { for d.parent[x] != x { d.parent[x] = d.parent[d.parent[x]] x = d.parent[x] } return x}func (d *DS) Union(a, b int) bool { a, b = d.Find(a), d.Find(b) if a == b { return false } if d.size[a] < d.size[b] { a, b = b, a } d.parent[b] = a d.size[a] += d.size[b] return true}func main() { d := NewDS(5) fmt.Println(d.Union(0, 1), d.Union(1, 2), d.Union(0, 2)) fmt.Println(d.Find(0) == d.Find(2), d.Find(0) == d.Find(4))}Find uses path halving to shorten chains; Union attaches the smaller group to the larger one. Repeated unions of already connected elements return false. Size is meaningful at roots. With both optimizations, a sequence has near-constant amortized operation cost (inverse Ackermann bound), not a constant worst-case guarantee for each call. Inputs must be valid indices; n must be nonnegative.
Expected output:
true true falsetrue falseDetect a cycle in an undirected graph
package main
import ( "fmt")
func root(p []int, x int) int { for p[x] != x { x = p[x] } return x}func main() { p := []int{0, 1, 2, 3} for _, e := range [][2]int{{0, 1}, {1, 2}, {0, 2}} { a, b := root(p, e[0]), root(p, e[1]) if a == b { fmt.Println("cycle") continue } p[b] = a } fmt.Println(root(p, 3) == root(p, 0))}Before each edge is added, equal representatives mean a path already exists between the endpoints, so adding the edge closes a cycle (for a simple undirected graph). This small variant omits the optimizations. Disjoint sets do not generally support splitting groups or arbitrary edge deletion. Do not compare representative numbers to infer ordering.
Expected output:
cyclefalseTry it locally
Count connected components among 5 vertices after adding edges (0,1), (1,2), (0,2), (3,4). Start with 5 and decrement only when two distinct roots merge.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data structures 06: Use disjoint sets
Check the lesson objective before moving on.
What does equal Find results mean?
When should the component count decrease?