1722. Minimize Hamming Distance After Swap Operations Medium

@problem@discussion
#Array#Depth-First Search#Union Find



1/**
2 * [1722] Minimize Hamming Distance After Swap Operations
3 *
4 * 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.
5 * 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).
6 * Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source.
7 *  
8 * Example 1:
9 * 
10 * Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]
11 * Output: 1
12 * Explanation: source can be transformed the following way:
13 * - Swap indices 0 and 1: source = [<u>2</u>,<u>1</u>,3,4]
14 * - Swap indices 2 and 3: source = [2,1,<u>4</u>,<u>3</u>]
15 * The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
16 * 
17 * Example 2:
18 * 
19 * Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []
20 * Output: 2
21 * Explanation: There are no allowed swaps.
22 * The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
23 * 
24 * Example 3:
25 * 
26 * Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]
27 * Output: 0
28 * 
29 *  
30 * Constraints:
31 * 
32 * 	n == source.length == target.length
33 * 	1 <= n <= 10^5
34 * 	1 <= source[i], target[i] <= 10^5
35 * 	0 <= allowedSwaps.length <= 10^5
36 * 	allowedSwaps[i].length == 2
37 * 	0 <= ai, bi <= n - 1
38 * 	ai != bi
39 * 
40 */
41pub struct Solution {}
42
43// problem: https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/
44// discuss: https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/discuss/?currentPage=1&orderBy=most_votes&query=
45
46// submission codes start here
47
48impl Solution {
49    pub fn minimum_hamming_distance(source: Vec<i32>, target: Vec<i32>, allowed_swaps: Vec<Vec<i32>>) -> i32 {
50        0
51    }
52}
53
54// submission codes end
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn test_1722() {
62    }
63}
64


Back
© 2025 bowen.ge All Rights Reserved.