Groups of Strings LeetCode solution in Python
1class DSU:2def __init__(self, n):3self.root = list(range(n))45def find(self, x):6if self.root[x] != x:7self.root[x] = self.find(self.root[x])8return self.root[x]910def union(self, x, y):11self.root[self.find(x)] = self.find(y)121314class Solution:15def groupStrings(self, A: List[str]) -> List[int]:16c = collections.defaultdict(int)17for a in A:18c["".join(sorted(a))] += 11920A = list(set(["".join(sorted(a)) for a in A]))21n = len(A)2223idx = collections.defaultdict(int) # (binary representation -> index)24dsu = DSU(n) # dsu2526def add(base):27for i in range(26):28if not base & 1 << i:29yield base ^ 1 << i3031def dele(base):32for i in range(26):33if base & 1 << i:34if base - (1 << i) != 0:35yield base - (1 << i)3637def rep(base):38pre, new = [], []39for i in range(26):40if base & 1 << i:41pre.append(i)42else:43new.append(i)44for p in pre:45for n in new:46yield base - (1 << p) + (1 << n)4748for i, a in enumerate(A):49base = 050for ch in a:51base += 1 << ord(ch) - ord("a")52idx[base] = i5354for base in idx.keys():55for new in add(base):56if new in idx:57dsu.union(idx[base], idx[new])58for new in dele(base):59if new in idx:60dsu.union(idx[base], idx[new])61for new in rep(base):62if new in idx:63dsu.union(idx[base], idx[new])6465group = collections.defaultdict(int)66for a in A:67base = 068for ch in a:69base += 1 << ord(ch) - ord("a")70cnum = c[a]71group[dsu.find(idx[base])] += cnum7273return [len(group), max(group.values())]