Lesson 24 +30 XP

Disjoint Sets & Union-Find Algorithm

Disjoint Sets & Union-Find Algorithm

A Disjoint Set Union (DSU) data structure maintains a partition of elements into mutually disjoint sets (Si ∩ Sj = ∅ for i ≠ j) and supports equivalence-class queries:

  • MakeSet(x): Creates a new singleton set {x} with parent[x] = x.
  • FindSet(x): Returns the canonical representative (root) of the set containing x.
  • Union(x, y): Merges the sets containing x and y into one set.

Disjoint Set Union-FindDisjoint Set Union-Find

1. Naive vs Optimized Union-Find

  • Naive Linked/Tree Union: Attaching roots arbitrarily can create a skewed chain of height O(n), making FindSet take O(n) time.
  • Optimization 1-Union by Rank / Size: Always attach the root of the smaller rank (height upper bound) tree under the root of the larger rank tree. Guarantees tree height ≤ ⌊ log2 n ⌋.
  • Optimization 2-Path Compression: During FindSet(x), recursively set parent[x] = findSet(parent[x]), making every node on the lookup path point directly to the root!

Step-by-Step Trace (1..6)

  1. MakeSet(1..6): {1}, {2}, {3}, {4}, {5}, {6} (all ranks = 0).
  2. Union(1, 2): rank equal → parent[2] = 1, rank[1] = 1.
  3. Union(3, 4): parent[4] = 3, rank[3] = 1.
  4. Union(2, 4): find(2)=1, find(4)=3 (rank 1 == 1) → parent[3] = 1, rank[1] = 2.
  5. Find(4) with Path Compression: walks 4 → 3 → 1, sets parent[4] = 1 directly!

Combined Complexity

With both Union by Rank and Path Compression, any sequence of m operations on n elements runs in:

O(m · α(n))
where α(n) is the inverse Ackermann function (α(n) ≤ 4 for all practical n ≤ 1080) - effectively O(1) amortized per operation!

C
int parent[100], rnk[100];

void makeSet(int n) {
    for (int i = 0; i < n; i++) { parent[i] = i; rnk[i] = 0; }
}

int findSet(int x) {
    if (parent[x] != x)
        parent[x] = findSet(parent[x]); // Path compression
    return parent[x];
}

void unionSets(int x, int y) {
    int rx = findSet(x), ry = findSet(y);
    if (rx == ry) return;
    if (rnk[rx] < rnk[ry]) parent[rx] = ry;
    else if (rnk[rx] > rnk[ry]) parent[ry] = rx;
    else { parent[ry] = rx; rnk[rx]++; }
}
💡 Tip

DSU is the core engine behind Kruskal's Minimum Spanning Tree algorithm and cycle detection in undirected graphs (if findSet(u) == findSet(v) before adding edge (u, v), a cycle exists!).

Notes' 8-Element Trace (union by rank + path compression)

Start: every element is its own root, rank 0. union(a, b) links the root of smaller rank under the root of larger rank; on a tie the first root becomes the parent and its rank grows by 1.

Operationparent[1..8]Ranks that changed
start1 2 3 4 5 6 7 8all 0
union(1,2)1 1 3 4 5 6 7 8rank[1] = 1
union(2,3)1 1 1 4 5 6 7 8find(2) = 1 has rank 1 &gt; rank[3] = 0
union(4,5)1 1 1 4 4 6 7 8rank[4] = 1
union(5,6)1 1 1 4 4 4 7 8-
union(7,8)1 1 1 4 4 4 7 7rank[7] = 1
union(4,8)1 1 1 4 4 4 4 7roots 4 and 7 tie at rank 1 → 7 under 4, rank[4] = 2
union(1,8)4 1 1 4 4 4 4 4find(8) compresses 8 → 4; rank[1] = 1 &lt; 2, so 1 goes under 4

Final forest: one set with root 4; parents 1→4, 2→1, 3→1, 5→4, 6→4, 7→4, 8→4. Height is 2 even though 8 elements were united.

Union by Size (alternative to rank)

Keep size[root] = number of elements in the tree. Attach the root of the smaller tree under the root of the larger one and add the sizes:

C
void unionBySize(int a, int b) {
    int x = find(a), y = find(b);
    if (x == y) return;
    if (size[x] < size[y]) { int t = x; x = y; y = t; }
    parent[y] = x;           /* smaller tree goes under larger */
    size[x] += size[y];
}

Every element's depth increases only when its tree at least doubles in size, so depth ≤ log₂ n-the same guarantee as union by rank.

Application: Network Connectivity

Computers 1…8 and cables arriving one at a time: (1,2), (2,3), (4,5), (5,6), (7,8). Question: &quot;can 3 talk to 6?&quot; → find(3) = 1, find(6) = 4, different roots → no. After the cable (4,8) and then (1,8): find(3) = find(6) = 4 → yes. Each query and each new cable costs almost O(1) amortized. The same idea detects cycles in Kruskal's algorithm, finds connected components, and groups pixels in image processing.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is a Disjoint Set? Explain the Union-Find algorithm with Union by Rank and Path Compression in C. (7.5 Marks)
  • Write: MakeSet, FindSet, Union definitions, 1..6 step-by-step trace, parent[]/rnk[] C code, and O(m · α(n)) amortized complexity.
  • Q2. How is Union-Find used to detect cycles in an undirected graph? (5 Marks)
  • Write: Iterate over each edge (u, v): if findSet(u) == findSet(v), a cycle is detected; otherwise unionSets(u, v).