test_reference_unionfind

Union-Find / Disjoint Set Union

The Union-Find (or Disjoint Set Union, DSU) data structure maintains a collection of disjoint sets and supports two primary operations:

With path compression and union by rank, both operations achieve near-constant amortized time:

α(n)O(1)(inverse Ackermann function)\alpha(n) \approx O(1) \quad \text{(inverse Ackermann function)}

The parent array encodes a forest of trees. For any element xx:

Find(x)={xif parent[x]=xFind(parent[x])otherwise\text{Find}(x) = \begin{cases} x & \text{if } parent[x] = x \\ \text{Find}(parent[x]) & \text{otherwise} \end{cases}

Union by rank ensures the shorter tree is attached under the taller one:

Union(x,y):if rank[rx]<rank[ry],  parent[rx]ry\text{Union}(x, y): \quad \text{if } rank[r_x] < rank[r_y], \; parent[r_x] \leftarrow r_y
Edge from node 0 to node 1Edge from node 1 to node 2Edge from node 3 to node 4Edge from node 5 to node 6Edge from node 6 to node 7Edge from node 2 to node 3Edge from node 4 to node 501234567startend

Step-by-Step Animation

We process edges one at a time, performing Union operations. The animation shows the graph, the parent[]parent[] array, the rank[]rank[] array, and a variable watch panel tracking the current operation.

Step 1 / 18

Complexity Analysis

OperationNaiveWith Optimizations
FindO(n)O(n)O(α(n))O(\alpha(n))
UnionO(n)O(n)O(α(n))O(\alpha(n))
mm operations on nn elementsO(mn)O(mn)O(mα(n))O(m \cdot \alpha(n))
SpaceO(n)O(n)O(n)O(n)

Where α(n)\alpha(n) is the inverse Ackermann function, which grows so slowly that α(n)4\alpha(n) \leq 4 for all practical values of nn (up to 222655362^{2^{2^{65536}}}).

Key optimizations:

  1. Path compression: During Find, make every node on the path point directly to the root.
  2. Union by rank: Always attach the shorter tree under the taller one to keep trees balanced.

Together, these guarantee that any sequence of mm Union/Find operations on nn elements takes O(mα(n))O(m \cdot \alpha(n)) time, which is effectively O(m)O(m) in practice.