#839

Similar String Groups

Hard
ArrayHash TableStringDepth-First SearchBreadth-First SearchUnion-FindHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

Using a union-find (disjoint set) data structure allows us to group similar strings efficiently. We can union strings that are similar and count the distinct groups at the end.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a union-find structure to manage string groups.
  2. 2Step 2: For each pair of strings, if they are similar, union them in the structure.
  3. 3Step 3: Count the number of unique roots in the union-find structure to determine the number of groups.
solution.py41 lines
1# Full working Python code
2class UnionFind:
3    def __init__(self, size):
4        self.parent = list(range(size))
5
6    def find(self, x):
7        if self.parent[x] != x:
8            self.parent[x] = self.find(self.parent[x])
9        return self.parent[x]
10
11    def union(self, x, y):
12        rootX = self.find(x)
13        rootY = self.find(y)
14        if rootX != rootY:
15            self.parent[rootY] = rootX
16
17def are_similar(s1, s2):
18    if s1 == s2:
19        return True
20    diff = []
21    for a, b in zip(s1, s2):
22        if a != b:
23            diff.append((a, b))
24        if len(diff) > 2:
25            return False
26    return len(diff) == 2 and diff[0] == diff[1][::-1]
27
28def num_similar_groups(strs):
29    n = len(strs)
30    uf = UnionFind(n)
31
32    for i in range(n):
33        for j in range(i + 1, n):
34            if are_similar(strs[i], strs[j]):
35                uf.union(i, j)
36
37    groups = len(set(uf.find(i) for i in range(n)))
38    return groups
39
40# Example usage
41print(num_similar_groups(['tars', 'rats', 'arts', 'star']))  # Output: 2

Complexity note: The time complexity remains O(n²) due to the pairwise comparison of strings. However, the space complexity is O(n) because we store the parent array for union-find operations.

  • 1Understanding the similarity condition is crucial for forming groups.
  • 2Union-Find is a powerful technique for grouping connected components.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.