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

Implementing a generic Union-Find (Disjoint Set) in Swift is a great way to manage a collection of disjoint sets and efficiently handle union and find operations. The Union-Find data structure supports two primary operations: union, which merges two sets, and find, which identifies the representative of a set. Here’s how you can implement it in Swift.

class UnionFind { private var parent: [T: T] = [:] private var rank: [T: Int] = [:] func find(_ element: T) -> T { if parent[element] == nil { parent[element] = element rank[element] = 0 } if parent[element] != element { parent[element] = find(parent[element]!) } return parent[element]! } func union(_ element1: T, _ element2: T) { let root1 = find(element1) let root2 = find(element2) if root1 != root2 { if rank[root1]! > rank[root2]! { parent[root2] = root1 } else if rank[root1]! < rank[root2]! { parent[root1] = root2 } else { parent[root2] = root1 rank[root1]! += 1 } } } } // Example Usage let uf = UnionFind() uf.union("A", "B") print(uf.find("A")) // Output: A print(uf.find("B")) // Output: A uf.union("B", "C") print(uf.find("C")) // Output: A

Swift Union-Find Disjoint Set Generic Data Structure Algorithms