How do I implement a union-find (disjoint set) in Swift?

The union-find (disjoint set) data structure is a powerful tool for managing a partition of a set into disjoint subsets. It supports two main operations, find and union, allowing you to efficiently determine which subset a particular element is in and to merge two subsets into a single subset. This data structure is commonly used in algorithms such as Kruskal's algorithm for finding minimum spanning trees.

class UnionFind { private var parent: [Int] private var rank: [Int] init(size: Int) { parent = Array(0.. Int { if parent[p] != p { parent[p] = find(parent[p]) // Path compression } return parent[p] } func union(_ p: Int, _ q: Int) { let rootP = find(p) let rootQ = find(q) if rootP != rootQ { // Union by rank if rank[rootP] > rank[rootQ] { parent[rootQ] = rootP } else if rank[rootP] < rank[rootQ] { parent[rootP] = rootQ } else { parent[rootQ] = rootP rank[rootP] += 1 } } } }

union-find disjoint set data structure path compression union by rank algorithms