A disjoint set, is a data structure that keeps track of a partition of a set into disjoint subsets. It defines three primary operations:
template <class T>
class DisjointSet {
public:
DisjointSet();
// Create a new set with a single element
void makeSet(const T& element);
// Find the representative of the set containing the element
T find(const T& element);
// Union the sets containing element1 and element2
void unionSets(const T& element1, const T& element2);
}
A common implementation of the disjoint set data structure is using a forest of trees. Each tree represents a subset, and the root of the tree is the representative of that subset. The Find operation traverses up the tree to find the root, while the Union operation links the roots of two trees together.
To improve the efficiency of the disjoint set operations, two optimizations are commonly used:
With these optimizations, the amortized time complexity for each operation is nearly constant, specifically