#1722
Minimize Hamming Distance After Swap Operations
MediumArrayDepth-First SearchUnion-FindUnion-FindGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of generating all permutations, we can treat the problem as a graph where each index can be connected through allowed swaps. By identifying connected components, we can determine which elements can be rearranged freely and calculate the minimum Hamming distance based on those components.
⚙️
Algorithm
3 steps- 1Step 1: Use Union-Find (Disjoint Set Union) to group indices based on allowed swaps.
- 2Step 2: For each connected component, collect the values from the source and target arrays.
- 3Step 3: Count the frequency of each value in both collections and compute the minimum Hamming distance by matching frequencies.
solution.py38 lines
1# Full working Python code
2class UnionFind:
3 def __init__(self, n):
4 self.parent = list(range(n))
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 minHammingDistance(source, target, allowedSwaps):
18 n = len(source)
19 uf = UnionFind(n)
20
21 for a, b in allowedSwaps:
22 uf.union(a, b)
23
24 groups = {}
25 for i in range(n):
26 root = uf.find(i)
27 if root not in groups:
28 groups[root] = ([], [])
29 groups[root][0].append(source[i])
30 groups[root][1].append(target[i])
31
32 min_distance = 0
33 for group in groups.values():
34 source_count = Counter(group[0])
35 target_count = Counter(group[1])
36 min_distance += sum((source_count - target_count).values())
37
38 return min_distanceℹ
Complexity note: The complexity is O(n) because we perform union-find operations which are nearly constant time, and we only traverse the arrays a few times to count frequencies.
- 1The problem can be visualized as a graph where indices are nodes and allowed swaps are edges.
- 2Connected components can be rearranged freely, allowing us to minimize mismatches effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.