You are given two integer arrays, source and target, both of length n.
You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi(0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order.
The Hamming distance of two arrays of the same length, source and
target, is the number of positions where the elements are different.
Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i](0-indexed).
Return _theminimum Hamming distance of _sourceandtarget _after performingany amount of swap operations on array _source.
Input: source =[1,2,3,4], target =[2,1,4,5], allowedSwaps =[[0,1],[2,3]]Output: 1Explanation: source can be transformed the following way:- Swap indices 0 and 1: source =[_2_ ,_1_ ,3,4]- Swap indices 2 and 3: source =[2,1,_4_ ,_3_]The Hamming distance of source and target is1 as they differ in1 position: index 3.
Input: source =[1,2,3,4], target =[1,3,2,4], allowedSwaps =[]Output: 2Explanation: There are no allowed swaps.The Hamming distance of source and target is2 as they differ in2 positions: index 1 and index 2.
Allowed swaps form connected components in the array. Within each component, any permutation is possible, so we can match as many elements as possible between source and target in each component. The minimum Hamming distance is the number of unmatched elements after optimal matching in each component.
classSolution {
funminimumHammingDistance(source: IntArray, target: IntArray, allowedSwaps: Array<IntArray>): Int {
val n = source.size
val parent = IntArray(n) { it }
funfind(x: Int): Int {
if (parent[x] != x) parent[x] = find(parent[x])
return parent[x]
}
for (s in allowedSwaps) parent[find(s[0])] = find(s[1])
val groups = mutableMapOf<Int, MutableList<Int>>()
for (i in0 until n) groups.getOrPut(find(i)) { mutableListOf() }.add(i)
var ans = 0for (idxs in groups.values) {
val freq = mutableMapOf<Int, Int>()
for (i in idxs) freq[source[i]] = freq.getOrDefault(source[i], 0) + 1for (i in idxs) {
if (freq.getOrDefault(target[i], 0) > 0) freq[target[i]] = freq[target[i]]!! - 1else ans++ }
}
return ans
}
}
defminimum_hamming_distance(source: list[int], target: list[int], allowed_swaps: list[list[int]]) -> int:
n = len(source)
parent = list(range(n))
deffind(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
for a, b in allowed_swaps:
parent[find(a)] = find(b)
groups = {}
for i in range(n):
root = find(i)
groups.setdefault(root, []).append(i)
ans =0for idxs in groups.values():
freq = {}
for i in idxs:
freq[source[i]] = freq.get(source[i], 0) +1for i in idxs:
if freq.get(target[i], 0):
freq[target[i]] -=1else:
ans +=1return ans