Open In App

Disjoint Set Union (Randomized Algorithm)

A Disjoint set union is an algorithm that is used to manage a collection of disjoint sets. A disjoint set is a set in which the elements are not in any other set. Also, known as union-find or merge-find.

The disjoint set union algorithm allows you to perform the following operations efficiently:



There are several ways to implement the disjoint set union algorithm, including the use of a randomized algorithm. Here is one way to implement the disjoint set union algorithm using a randomized approach:

Overall, the disjoint set union algorithm is a useful tool for efficiently managing a collection of disjoint sets. It can be used in a variety of applications, including clustering, graph coloring, and image segmentation.



Here is an example of the disjoint set union algorithm implemented in Python:




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
class GFG {
public:
    vector<int> parent;
    vector<int> size;
 
public:
    GFG(int n)
    {
        parent.resize(n);
        size.resize(n);
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
    }
 
    int find(int x)
    {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
 
    void union_(int x, int y)
    {
        int root_x = find(x);
        int root_y = find(y);
        if (root_x == root_y) {
            return;
        }
 
        if (rand() % 2 == 0) {
            int temp = root_x;
            root_x = root_y;
            root_y = temp;
        }
 
        parent[root_y] = root_x;
        size[root_x] += size[root_y];
    }
};
 
int main()
{
    GFG ds(5);
 
    cout << "Initial parent array: ";
    for (int i = 0; i < 5; i++)
        cout << ds.parent[i] << " ";
    cout << endl;
 
    // Union the sets containing elements 0 and 1
    ds.union_(0, 1);
    cout << "Parent array after union(0, 1): ";
    for (int i = 0; i < 5; i++)
        cout << ds.parent[i] << " ";
    cout << endl;
 
    // Union the sets containing elements 1 and 2
    ds.union_(1, 2);
    cout << "Parent array after union(1, 2): ";
    for (int i = 0; i < 5; i++)
        cout << ds.parent[i] << " ";
    cout << endl;
 
    // Union the sets containing elements 3 and 4
    ds.union_(3, 4);
    cout << "Parent array after union(3, 4): ";
    for (int i = 0; i < 5; i++)
        cout << ds.parent[i] << " ";
    cout << endl;
 
    cout << "Root of set containing element 0: "
         << ds.find(0) << endl;
    cout << "Root of set containing element 3: "
         << ds.find(3) << endl;
 
    return 0;
}
 
// Note: As we are using random() function,
//          the output values may differ.
 
// This code is contributed by Prasad Kandekar(prasad264)




// Java code for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  int[] parent;
  int[] size;
  Random rand = new Random();
 
  public GFG(int n)
  {
    parent = new int[n];
    size = new int[n];
    for (int i = 0; i < n; i++) {
      parent[i] = i;
      size[i] = 1;
    }
  }
 
  public int find(int x)
  {
    if (parent[x] != x) {
      parent[x] = find(parent[x]);
    }
    return parent[x];
  }
 
  public void union(int x, int y)
  {
    int rootX = find(x);
    int rootY = find(y);
    if (rootX == rootY) {
      return;
    }
 
    if (rand.nextInt(2) == 0) {
      int temp = rootX;
      rootX = rootY;
      rootY = temp;
    }
 
    parent[rootX] = rootY;
    size[rootY] += size[rootX];
  }
 
  public static void main(String[] args)
  {
    GFG ds = new GFG(5);
 
    System.out.println("Initial parent array: "
                       + Arrays.toString(ds.parent));
 
    // Union the sets containing elements 0 and 1
    ds.union(0, 1);
    System.out.println(
      "Parent array after union(0, 1): "
      + Arrays.toString(ds.parent));
 
    // Union the sets containing elements 1 and 2
    ds.union(1, 2);
    System.out.println(
      "Parent array after union(1, 2): "
      + Arrays.toString(ds.parent));
 
    // Union the sets containing elements 3 and 4
    ds.union(3, 4);
    System.out.println(
      "Parent array after union(3, 4): "
      + Arrays.toString(ds.parent));
 
    System.out.println(
      "Root of set containing element 0: "
      + ds.find(0));
    System.out.println(
      "Root of set containing element 3: "
      + ds.find(3));
  }
}
 
// Note: As we are using random() function,
//          the output values may differ.
 
// This code is contributed by lokesh.




# Python code for the above approach
import random
 
 
class DisjointSetUnion:
    def __init__(self, n):
        self.parent = [i for i in range(n)]
        self.size = [1] * n
 
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
 
    def union(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)
        if root_x == root_y:
            return
 
        if random.randint(0, 1) == 0:
            root_x, root_y = root_y, root_x
 
        self.parent[root_y] = root_x
        self.size[root_x] += self.size[root_y]
 
# Driver code
 
 
ds = DisjointSetUnion(5)
 
print("Initial parent array: ", ds.parent)
 
# Union the sets containing elements
# 0 and 1
ds.union(0, 1)
print("Parent array after union(0, 1): ", ds.parent)
 
# Union the sets containing elements
# 1 and 2
ds.union(1, 2)
print("Parent array after union(1, 2): ", ds.parent)
 
# Union the sets containing elements
# 3 and 4
ds.union(3, 4)
print("Parent array after union(3, 4): ", ds.parent)
 
print("Root of set containing element 0: ", ds.find(0))
 
print("Root of set containing element 3: ", ds.find(3))




// C# code for the above approach
using System;
 
public class GFG {
 
  int[] parent;
  int[] size;
  Random rand = new Random();
 
  public GFG(int n)
  {
    parent = new int[n];
    size = new int[n];
    for (int i = 0; i < n; i++) {
      parent[i] = i;
      size[i] = 1;
    }
  }
 
  public int Find(int x)
  {
    if (parent[x] != x) {
      parent[x] = Find(parent[x]);
    }
    return parent[x];
  }
 
  public void Union(int x, int y)
  {
    int rootX = Find(x);
    int rootY = Find(y);
    if (rootX == rootY) {
      return;
    }
 
    if (rand.Next(2) == 0) {
      int temp = rootX;
      rootX = rootY;
      rootY = temp;
    }
 
    parent[rootX] = rootY;
    size[rootY] += size[rootX];
  }
 
  static public void Main()
  {
 
    // Code
    GFG ds = new GFG(5);
 
    Console.WriteLine("Initial parent array: ["
                      + string.Join(", ", ds.parent)
                      + "]");
 
    // Union the sets containing elements 0 and 1
    ds.Union(0, 1);
    Console.WriteLine(
      "Parent array after union(0, 1): ["
      + string.Join(", ", ds.parent) + "]");
 
    // Union the sets containing elements 1 and 2
    ds.Union(1, 2);
    Console.WriteLine(
      "Parent array after union(1, 2): ["
      + string.Join(", ", ds.parent) + "]");
 
    // Union the sets containing elements 3 and 4
    ds.Union(3, 4);
    Console.WriteLine(
      "Parent array after union(3, 4): ["
      + string.Join(", ", ds.parent) + "]");
 
    Console.WriteLine(
      "Root of set containing element 0: "
      + ds.Find(0));
    Console.WriteLine(
      "Root of set containing element 3: "
      + ds.Find(3));
  }
}
 
// This code is contributed by lokeshmvs21.




// Javascript code for the above approach
class DisjointSetUnion {
    constructor(n) {
        this.parent = [...Array(n).keys()]
        this.size = Array(n).fill(1)
    }
 
    find(x) {
        if (this.parent[x] !== x) {
            this.parent[x] = this.find(this.parent[x])
        }
        return this.parent[x]
    }
 
    union(x, y) {
        let root_x = this.find(x)
        let root_y = this.find(y)
        if (root_x === root_y) {
            return
        }
 
        if (Math.floor(Math.random() * 2) === 0) {
            [root_x, root_y] = [root_y, root_x]
        }
 
        this.parent[root_y] = root_x
        this.size[root_x] += this.size[root_y]
    }
}
 
let ds = new DisjointSetUnion(5)
 
console.log("Initial parent array: ", ds.parent.join(" "))
 
// Union the sets containing elements
// 0 and 1
ds.union(0, 1)
console.log("Parent array after union(0, 1): ", ds.parent.join(" "))
 
// Union the sets containing elements
// 1 and 2
ds.union(1, 2)
console.log("Parent array after union(1, 2): ", ds.parent.join(" "))
 
// Union the sets containing elements
// 3 and 4
ds.union(3, 4)
console.log("Parent array after union(3, 4): ", ds.parent.join(" "))
 
console.log("Root of set containing element 0: ", ds.find(0))
 
console.log("Root of set containing element 3: ", ds.find(3))
 
//This code is contributed by shivamsharma215

Output
Initial parent array: 0 1 2 3 4 
Parent array after union(0, 1): 0 0 2 3 4 
Parent array after union(1, 2): 2 0 2 3 4 
Parent array after union(3, 4): 2 0 2 3 3 
Root of set containing element 0: 2
Root of set containing element 3: 3

Below is an implementation of the DisjointSetUnion class that uses randomized linking for the union operation:




#include <iostream>
#include <vector>
#include <random>
using namespace std;
 
// Define the DisjointSetUnion class
class DisjointSetUnion {
public:
    // Constructor that initializes the parent and size arrays
    DisjointSetUnion(int n) {
        parent = vector<int>(n);
        size = vector<int>(n, 1);
        for (int i = 0; i < n; i++) {
            parent[i] = i;
        }
    }
     
    // Find the root of the set containing element x
    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
     
    // Merge the sets containing elements x and y
    void unite(int x, int y) {
        int root_x = find(x);
        int root_y = find(y);
        if (root_x == root_y) {
            return;
        }
        // Randomly choose one root to be the parent of the other
        if (rand() % 2 == 0) {
            swap(root_x, root_y);
        }
        parent[root_y] = root_x;
        size[root_x] += size[root_y];
    }
     
private:
    vector<int> parent;
    vector<int> size;
};
 
// Driver code
int main() {
    DisjointSetUnion ds(5);
    cout << "Initial parent array: ";
    for (int i = 0; i < 5; i++) {
        cout << ds.find(i) << " ";
    }
    cout << endl;
     
    // Union the sets containing elements 0 and 1
    ds.unite(0, 1);
    cout << "Parent array after union(0, 1): ";
    for (int i = 0; i < 5; i++) {
        cout << ds.find(i) << " ";
    }
    cout << endl;
     
    // Union the sets containing elements 1 and 2
    ds.unite(1, 2);
    cout << "Parent array after union(1, 2): ";
    for (int i = 0; i < 5; i++) {
        cout << ds.find(i) << " ";
    }
    cout << endl;
     
    // Union the sets containing elements 3 and 4
    ds.unite(3, 4);
    cout << "Parent array after union(3, 4): ";
    for (int i = 0; i < 5; i++) {
        cout << ds.find(i) << " ";
    }
    cout << endl;
     
    // Find the root of the set containing element 0
    cout << "Root of set containing element 0: " << ds.find(0) << endl;
     
    // Find the root of the set containing element 3
    cout << "Root of set containing element 3: " << ds.find(3) << endl;
     
    return 0;
}




import java.util.Arrays;
import java.util.Random;
 
public class DisjointSetUnion {
    private int[] parent;
    private int[] size;
 
    public DisjointSetUnion(int n)
    {
        this.parent = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
        }
        this.size = new int[n];
        Arrays.fill(size, 1);
    }
 
    public int find(int x)
    {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
 
    public void union(int x, int y)
    {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX == rootY) {
            return;
        }
 
        Random rand = new Random();
        if (rand.nextInt(2) == 0) {
            int temp = rootX;
            rootX = rootY;
            rootY = temp;
        }
 
        parent[rootY] = rootX;
        size[rootX] += size[rootY];
    }
 
    public static void main(String[] args)
    {
        DisjointSetUnion ds = new DisjointSetUnion(5);
        System.out.println("Initial parent array: "
                           + Arrays.toString(ds.parent));
        ds.union(0, 1);
        System.out.println(
            "Parent array after union(0, 1): "
            + Arrays.toString(ds.parent));
        ds.union(1, 2);
        System.out.println(
            "Parent array after union(1, 2): "
            + Arrays.toString(ds.parent));
        ds.union(3, 4);
        System.out.println(
            "Parent array after union(3, 4): "
            + Arrays.toString(ds.parent));
        System.out.println(
            "Root of set containing element 0: "
            + ds.find(0));
        System.out.println(
            "Root of set containing element 3: "
            + ds.find(3));
    }
}




import random
 
 
class DisjointSetUnion:
    def __init__(self, n):
        self.parent = [i for i in range(n)]
        self.size = [1] * n
 
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
 
    def union(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)
        if root_x == root_y:
            return
 
        if random.randint(0, 1) == 0:
            root_x, root_y = root_y, root_x
 
        self.parent[root_y] = root_x
        self.size[root_x] += self.size[root_y]
 
 
# Driver code
ds = DisjointSetUnion(5)
 
print("Initial parent array: ", ds.parent)
 
# Union the sets containing elements
# 0 and 1
ds.union(0, 1)
print("Parent array after union(0, 1): ", ds.parent)
 
# Union the sets containing elements
# 1 and 2
ds.union(1, 2)
print("Parent array after union(1, 2): ", ds.parent)
 
# Union the sets containing elements
# 3 and 4
ds.union(3, 4)
print("Parent array after union(3, 4): ", ds.parent)
 
print("Root of set containing element 0: ", ds.find(0))
 
print("Root of set containing element 3: ", ds.find(3))




// C# code for the approach
 
using System;
using System.Collections.Generic;
 
// Define the DisjointSetUnion class
class DisjointSetUnion {
    private List<int> parent;
    private List<int> size;
 
    // Constructor that initializes the parent and size
    // arrays
    public DisjointSetUnion(int n)
    {
        parent = new List<int>(n);
        size = new List<int>(n);
        for (int i = 0; i < n; i++) {
            parent.Add(i);
            size.Add(1);
        }
    }
 
    // Find the root of the set containing element x
    public int Find(int x)
    {
        if (parent[x] != x) {
            parent[x] = Find(parent[x]);
        }
        return parent[x];
    }
 
    // Merge the sets containing elements x and y
    public void Unite(int x, int y)
    {
        int root_x = Find(x);
        int root_y = Find(y);
        if (root_x == root_y) {
            return;
        }
        // Randomly choose one root to be the parent of the
        // other
        if (new Random().Next(2) == 0) {
            int temp = root_x;
            root_x = root_y;
            root_y = temp;
        }
        parent[root_y] = root_x;
        size[root_x] += size[root_y];
    }
}
 
// Driver code
class Program {
    static void Main(string[] args)
    {
        DisjointSetUnion ds = new DisjointSetUnion(5);
        Console.Write("Initial parent array: ");
        for (int i = 0; i < 5; i++) {
            Console.Write(ds.Find(i) + " ");
        }
        Console.WriteLine();
 
        // Union the sets containing elements 0 and 1
        ds.Unite(0, 1);
        Console.Write("Parent array after union(0, 1): ");
        for (int i = 0; i < 5; i++) {
            Console.Write(ds.Find(i) + " ");
        }
        Console.WriteLine();
 
        // Union the sets containing elements 1 and 2
        ds.Unite(1, 2);
        Console.Write("Parent array after union(1, 2): ");
        for (int i = 0; i < 5; i++) {
            Console.Write(ds.Find(i) + " ");
        }
        Console.WriteLine();
 
        // Union the sets containing elements 3 and 4
        ds.Unite(3, 4);
        Console.Write("Parent array after union(3, 4): ");
        for (int i = 0; i < 5; i++) {
            Console.Write(ds.Find(i) + " ");
        }
        Console.WriteLine();
 
        // Find the root of the set containing element 0
        Console.WriteLine(
            "Root of set containing element 0: "
            + ds.Find(0));
 
        // Find the root of the set containing element 3
        Console.WriteLine(
            "Root of set containing element 3: "
            + ds.Find(3));
    }
}




class DisjointSetUnion {
  // Constructor that initializes the parent and size arrays
  constructor(n) {
    this.parent = new Array(n); // Create an array of n elements to store the parent of each node
    for (let i = 0; i < n; i++) {
      this.parent[i] = i; // Initialize the parent of each node to itself
    }
    this.size = new Array(n).fill(1); // Create an array of n elements to store the size of each set, initialized to 1 for each node
  }
 
  // Method to find the root of the set containing x
  find(x) {
    if (this.parent[x] !== x) {
      // If x is not the root of its set, recursively find the root and update the parent of x to the root to compress the path
      this.parent[x] = this.find(this.parent[x]);
    }
    return this.parent[x]; // Return the root of the set containing x
  }
 
  // Method to union the sets containing x and y
  union(x, y) {
    let rootX = this.find(x); // Find the root of the set containing x
    let rootY = this.find(y); // Find the root of the set containing y
    if (rootX === rootY) {
      // If x and y are already in the same set, do nothing
      return;
    }
 
    if (Math.floor(Math.random() * 2) === 0) {
      // Randomly choose which root becomes the new parent
      [rootX, rootY] = [rootY, rootX]; // Swap rootX and rootY
    }
 
    this.parent[rootY] = rootX; // Set the new parent of the set containing y to the root of the set containing x
    this.size[rootX] += this.size[rootY]; // Update the size of the set containing x to include the size of the set containing y
  }
}
 
// Example usage of the DisjointSetUnion class
const ds = new DisjointSetUnion(5); // Create a new DisjointSetUnion object with 5 nodes
console.log("Initial parent array: " + ds.parent); // Print the initial parent array
ds.union(0, 1); // Union the sets containing 0 and 1
console.log("Parent array after union(0, 1): " + ds.parent); // Print the parent array after the union
ds.union(1, 2); // Union the sets containing 1 and 2
console.log("Parent array after union(1, 2): " + ds.parent); // Print the parent array after the union
ds.union(3, 4); // Union the sets containing 3 and 4
console.log("Parent array after union(3, 4): " + ds.parent); // Print the parent array after the union
console.log("Root of set containing element 0: " + ds.find(0)); // Find and print the root of the set containing 0
console.log("Root of set containing element 3: " + ds.find(3)); // Find and print the root of the set containing 3

Output
Initial parent array:  [0, 1, 2, 3, 4]
Parent array after union(0, 1):  [0, 0, 2, 3, 4]
Parent array after union(1, 2):  [0, 0, 0, 3, 4]
Parent array after union(3, 4):  [0, 0, 0, 4, 4]
Root of set containing element 0:  0
Root of set containing element 3:  4

The output of DisjointSetUnion class that uses randomized linking for the union operation:

Initial parent array:  [0, 1, 2, 3, 4]
Parent array after union(0, 1):  [0, 0, 2, 3, 4]
Parent array after union(1, 2):  [0, 0, 0, 3, 4]
Parent array after union(3, 4):  [0, 0, 0, 3, 3]
Root of set containing element 0:  0
Root of set containing element 3:  3

One-try and two-try variations of splitting:

The one-try and two-try variations of splitting are techniques that can be used to improve the performance of the disjoint set union (also known as union-find or merge-find) algorithm in certain cases. These variations are used to optimize the find operation, which is used to determine which set a given element belongs to.

Here is an example of how the one-try variation of splitting might be implemented:




int find(int x)
{
    if (parent[x] != x) {
        int root = parent[x];
        parent[x] = find(parent[x]);
        if (parent[x] == x) {
            return root;
        }
    }
    return parent[x];
}
 
// This code is contributed by akashish__




public int find(int x)
{
    if (parent[x] != x) {
        int root = parent[x];
        parent[x] = find(parent[x]);
        if (parent[x] == x) {
            return root;
        }
    }
    return parent[x];
}




def find(self, x):
    if self.parent[x] != x:
        self.parent[x], root = self.find(self.parent[x]), self.parent[x]
        if self.parent[x] == x:
            return root
    return self.parent[x]




// This function finds the root of the disjoint set that x belongs to.
// It uses path compression technique to optimize the search.
 
int find(int x)
{
// Check if x is not already the root of its disjoint set
    if (parent[x] != x) {
    // If not, then find the root of its parent using recursion
    int root = parent[x];
    parent[x] = find(parent[x]);
    // If the root of parent is the same as x, it means we have reached
    // the root of the disjoint set. Return the original root.
    if (parent[x] == x) {
        return root;
          }
    }
    // If x is already the root of its disjoint set, return x.
    return parent[x];
}




function find(x)
{
    if (parent[x] != x) {
        let root = parent[x];
        parent[x] = find(parent[x]);
        if (parent[x] == x) {
            return root;
        }
    }
    return parent[x];
}
 
// This code is contributed by akashish__

The two-try variation of splitting is similar to the one-try variation, but it involves following the parent links twice instead of once. This can further improve the performance of the find operation in some cases.

Overall, the one-try and two-try variations of splitting are techniques that can be used to optimize the find operation in the disjoint set union algorithm. They can be useful in cases where the tree structure of the sets is highly unbalanced and the find operation is taking a long time. However, they may not always provide a significant improvement in performance and may require additional memory and computation.

Analysis of linking and Analysis splitting:

Time complexity: O(alpha(n)) (for find operation)
Time complexity: O(alpha(n)) (for Union operation)

One variation of the disjoint set union algorithm is to use the one-try or two-try variations of splitting to optimize the find operation. These variations can improve the performance of the find operation in cases where the tree structure of the sets is highly unbalanced, but they may not always provide a significant improvement in performance and may require additional memory and computation.

Advantages over the sequential approach:

Disadvantages over sequential approach:

Overall, the disjoint set union algorithm is a very efficient and scalable data structure for managing a collection of disjoint sets. It is well-suited for large data sets and can be simpler to implement than the sequential approach. However, it may have slower performance and higher memory usage than the sequential approach for small data sets.


Article Tags :