Press "Enter" to skip to content

Posts published in “SP”

花花酱 LeetCode Disjoint set / Union Find Forest SP1

Disjoint-set/Union-find Forest

Find(x): find the root/cluster-id of x

Union(x, y): merge two clusters

Check whether two elements are in the same set or not in O(1)*.

Find: O(ɑ(n))* ≈ O(1)

Union: O(ɑ(n))* ≈ O(1)

Space: O(n)

Without optimization: Find: O(n)

Two key optimizations:

  1. Path compression: make tree flat
  2. Union by rank: merge low rank tree to high rank one

*: amortized

ɑ(.): inverse Ackermann function

 

Implementations:

C++

Java

Python

Union-Find Problems

References