- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 41 lines of Python from the credited upstream file 1202.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind:2 def __init__(self, n: int):3 self.id = list(range(n))4 self.rank = [0] * n5 6 def unionByRank(self, u: int, v: int) -> None:7 i = self.find(u)8 j = self.find(v)9 if i == j:10 return11 if self.rank[i] < self.rank[j]:12 self.id[i] = j13 elif self.rank[i] > self.rank[j]:14 self.id[j] = i15 else:16 self.id[i] = j17 self.rank[j] += 118 19 def find(self, u: int) -> int:20 if self.id[u] != u:21 self.id[u] = self.find(self.id[u])22 return self.id[u]23 24 25class Solution:26 def smallestStringWithSwaps(self, s: str, pairs: list[list[int]]) -> str:27 uf = UnionFind(len(s))28 indexToLetters = collections.defaultdict(list)29 30 for a, b in pairs:31 uf.unionByRank(a, b)32 33 for i, c in enumerate(s):34 indexToLetters[uf.find(i)].append(c)35 36 for key in indexToLetters.keys():37 indexToLetters[key].sort(reverse=True)38 39 return ''.join(indexToLetters[uf.find(i)].pop()40 for i in range(len(s)))41