- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 65 lines of Python from the credited upstream file similar-string-groups.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 1 loop block 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.
123 4import collections5import itertools6 7 8class UnionFind(object):9 def __init__(self, n):10 self.set = range(n)11 self.__size = n12 13 def find_set(self, x):14 if self.set[x] != x:15 self.set[x] = self.find_set(self.set[x]) 16 return self.set[x]17 18 def union_set(self, x, y):19 x_root, y_root = map(self.find_set, (x, y))20 if x_root == y_root:21 return False22 self.set[min(x_root, y_root)] = max(x_root, y_root)23 self.__size -= 124 return True25 26 def size(self):27 return self.__size28 29 30class Solution(object):31 def numSimilarGroups(self, A):32 def isSimilar(a, b):33 diff = 034 for x, y in itertools.izip(a, b):35 if x != y:36 diff += 137 if diff > 2:38 return False39 return diff == 240 41 N, L = len(A), len(A[0])42 union_find = UnionFind(N)43 if N < L*L:44 for (i1, word1), (i2, word2) in \45 itertools.combinations(enumerate(A), 2):46 if isSimilar(word1, word2):47 union_find.union_set(i1, i2)48 else:49 buckets = collections.defaultdict(list)50 lookup = set()51 for i in xrange(len(A)):52 word = list(A[i])53 if A[i] not in lookup:54 buckets[A[i]].append(i)55 lookup.add(A[i])56 for j1, j2 in itertools.combinations(xrange(L), 2):57 word[j1], word[j2] = word[j2], word[j1]58 buckets["".join(word)].append(i)59 word[j1], word[j2] = word[j2], word[j1]60 for word in A: 61 for i1, i2 in itertools.combinations(buckets[word], 2):62 union_find.union_set(i1, i2)63 return union_find.size()64 65