- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 63 lines of Python from the credited upstream file 2157.py.
- The implementation visibly relies on sequence storage.
- 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.count = n4 self.id = list(range(n))5 self.sz = [1] * n6 7 def unionBySize(self, u: int, v: int) -> None:8 i = self._find(u)9 j = self._find(v)10 if i == j:11 return12 if self.sz[i] < self.sz[j]:13 self.sz[j] += self.sz[i]14 self.id[i] = j15 else:16 self.sz[i] += self.sz[j]17 self.id[j] = i18 self.count -= 119 20 def _find(self, u: int) -> int:21 if self.id[u] != u:22 self.id[u] = self._find(self.id[u])23 return self.id[u]24 25 26class Solution:27 def groupStrings(self, words: list[str]) -> list[int]:28 uf = UnionFind(len(words))29 30 def getMask(s: str) -> int:31 mask = 032 for c in s:33 mask |= 1 << ord(c) - ord('a')34 return mask35 36 def getAddedMasks(mask: int):37 for i in range(26):38 if not (mask >> i & 1):39 yield mask | 1 << i40 41 def getDeletedMasks(mask: int):42 for i in range(26):43 if mask >> i & 1:44 yield mask ^ 1 << i45 46 maskToIndex = {getMask(word): i for i, word in enumerate(words)}47 deletedMaskToIndex = {}48 49 for i, word in enumerate(words):50 mask = getMask(word)51 for m in getAddedMasks(mask):52 if m in maskToIndex:53 uf.unionBySize(i, maskToIndex[m])54 for m in getDeletedMasks(mask):55 if m in maskToIndex:56 uf.unionBySize(i, maskToIndex[m])57 if m in deletedMaskToIndex:58 uf.unionBySize(i, deletedMaskToIndex[m])59 else:60 deletedMaskToIndex[m] = i61 62 return [uf.count, max(uf.sz)]63