Collection Kit

DisjointSet

Advanced

A DisjointSet (Union-Find) is a data structure that keeps track of a partition of a set into disjoint subsets, supporting union and find operations.

Import Statement
import { DisjointSet } from "collection-kit";

Key Features

  • Efficient Union and Find: Supports merging of sets and finding the representative of a set.
  • Dynamic Size: Can grow as new elements are added.

Common Operations

Find
Determine the representative of the set containing a specific element.
Union
Merge two sets into a single set.
Connected
Check if two elements belong to the same set.

Example Code

import { DisjointSet } from "collection-kit";

const ds = new DisjointSet(5);
ds.union(0, 1);
ds.union(1, 2);

console.log("Connected 0-2:", ds.connected(0, 2)); // true
console.log("Connected 0-3:", ds.connected(0, 3)); // false