|
| 1 | +/** |
| 2 | + * 1722. Minimize Hamming Distance After Swap Operations |
| 3 | + * https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two integer arrays, source and target, both of length n. You are also given an |
| 7 | + * array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to |
| 8 | + * swap the elements at index ai and index bi (0-indexed) of array source. Note that you can |
| 9 | + * swap elements at a specific pair of indices multiple times and in any order. |
| 10 | + * |
| 11 | + * The Hamming distance of two arrays of the same length, source and target, is the number of |
| 12 | + * positions where the elements are different. Formally, it is the number of indices i for |
| 13 | + * 0 <= i <= n-1 where source[i] != target[i] (0-indexed). |
| 14 | + * |
| 15 | + * Return the minimum Hamming distance of source and target after performing any amount of swap |
| 16 | + * operations on array source. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[]} source |
| 21 | + * @param {number[]} target |
| 22 | + * @param {number[][]} allowedSwaps |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var minimumHammingDistance = function(source, target, allowedSwaps) { |
| 26 | + const n = source.length; |
| 27 | + const parent = new Array(n).fill().map((_, i) => i); |
| 28 | + |
| 29 | + for (const [a, b] of allowedSwaps) { |
| 30 | + union(a, b); |
| 31 | + } |
| 32 | + |
| 33 | + const groups = new Map(); |
| 34 | + for (let i = 0; i < n; i++) { |
| 35 | + const root = find(i); |
| 36 | + if (!groups.has(root)) { |
| 37 | + groups.set(root, { source: [], target: [] }); |
| 38 | + } |
| 39 | + groups.get(root).source.push(source[i]); |
| 40 | + groups.get(root).target.push(target[i]); |
| 41 | + } |
| 42 | + |
| 43 | + let result = 0; |
| 44 | + for (const { source, target } of groups.values()) { |
| 45 | + const sourceCount = new Map(); |
| 46 | + for (const num of source) { |
| 47 | + sourceCount.set(num, (sourceCount.get(num) || 0) + 1); |
| 48 | + } |
| 49 | + for (const num of target) { |
| 50 | + const count = sourceCount.get(num) || 0; |
| 51 | + if (count === 0) { |
| 52 | + result++; |
| 53 | + } else { |
| 54 | + sourceCount.set(num, count - 1); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return result; |
| 60 | + |
| 61 | + function find(x) { |
| 62 | + if (parent[x] !== x) { |
| 63 | + parent[x] = find(parent[x]); |
| 64 | + } |
| 65 | + return parent[x]; |
| 66 | + } |
| 67 | + |
| 68 | + function union(x, y) { |
| 69 | + parent[find(x)] = find(y); |
| 70 | + } |
| 71 | +}; |
0 commit comments