[LeetCode] Minimize Hamming Distance After Swap Operations

1722. Minimize Hamming Distance After Swap Operations

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 the minimum Hamming distance of source and target after performing any amount of swap operations on array source.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
int uf[101010];
int find(int u) {
return uf[u] == u ? u : uf[u] = find(uf[u]);
}
void uni(int u, int v) {
int pu = find(u), pv = find(v);
uf[pu] = uf[pv] = min(pu,pv);
}
public:
int minimumHammingDistance(vector<int>& A, vector<int>& B, vector<vector<int>>& allowedSwaps) {
int n = A.size();
for(int i = 0; i < n; i++) uf[i] = i;
for(auto a : allowedSwaps) {
int u = a[0], v = a[1];
uni(u,v);
}
unordered_map<int, unordered_map<int, int>> freq;
for(int i = 0; i < n; i++) {
freq[find(i)][A[i]]++;
}
int res = 0;
for(int i = 0; i < n; i++) {
int f = find(i);
if(!freq[f][B[i]]) res++;
else freq[f][B[i]]--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/17/PS/LeetCode/minimize-hamming-distance-after-swap-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.