⬅ Previous Topic
Prim's Algorithm for Minimum Spanning TreeNext Topic ⮕
Kruskal's Algorithm - Minimum Spanning Tree⬅ Previous Topic
Prim's Algorithm for Minimum Spanning TreeNext Topic ⮕
Kruskal's Algorithm - Minimum Spanning TreeTopic Contents
The Disjoint Set (also called Union-Find) is a data structure used to manage a collection of non-overlapping sets. It supports two main operations:
Disjoint Set is particularly useful in problems involving connected components, cycle detection in graphs, and Kruskal's algorithm for Minimum Spanning Tree.
To improve efficiency, it uses two optimizations:
class DisjointSet {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.rank = Array(n).fill(0);
}
find(x) {
if (this.parent[x] !== x) {
this.parent[x] = this.find(this.parent[x]); // Path Compression
}
return this.parent[x];
}
union(x, y) {
let rootX = this.find(x);
let rootY = this.find(y);
if (rootX === rootY) return;
// Union by Rank
if (this.rank[rootX] < this.rank[rootY]) {
this.parent[rootX] = rootY;
} else if (this.rank[rootX] > this.rank[rootY]) {
this.parent[rootY] = rootX;
} else {
this.parent[rootY] = rootX;
this.rank[rootX]++;
}
}
}
const ds = new DisjointSet(5);
ds.union(0, 1);
ds.union(1, 2);
console.log("Find(2):", ds.find(2)); // Should be 0
console.log("Find(3):", ds.find(3)); // Should be 3 (not connected)
⬅ Previous Topic
Prim's Algorithm for Minimum Spanning TreeNext Topic ⮕
Kruskal's Algorithm - Minimum Spanning TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.