Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Disjoint Sets ADT

User image

Published by

sanya sanya

Published at: 4th Aug, 2023
1.21 mins read

• MAKESET(X): Creates a new set containing a single element X.

• UNION(X, Y): Creates a new set containing the elements X and Y in their union and deletes the sets containing the elements X and Y.

• FIND(X): Returns the name of the set containing the element X.

Example:

#include

#include <unordered_map>

using namespace std;

class DisjointSets {

private:

unordered_map<int, int> parent; // Stores the parent of each element

public:

// Constructor

DisjointSets() {}

// Creates a new set containing a single element ‘x’

void makeSet(int x) {

parent[x] = x;

}

// Returns the name of the set containing the element ‘x’

int find(int x) {

if (parent.find(x) == parent.end())

return -1; // Element not found in any set

// If ‘x’ is not the representative (parent) of the set, recursively find the parent

if (parent[x] != x)

parent[x] = find(parent[x]); // Path compression

return parent[x];

}

// Creates a new set containing the elements ‘x’ and ‘y’ in their union

// and deletes the sets containing the elements ‘x’ and ‘y’

void unionSets(int x, int y) {

int parentX = find(x);

int parentY = find(y);

if (parentX == -1 || parentY == -1 || parentX == parentY)

return; // Elements not found or already in the same set

parent[parentX] = parentY;

}

};

Library

WEB DEVELOPMENT

FAANG QUESTIONS