Skip to content

Practice Minimize Hamming Distance After Swap Operations

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#1722
LeetCode Problem

Minimize Hamming Distance After Swap Operations

Problem Statement

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.

Source: Minimize Hamming Distance After Swap Operations on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]
Output
1

# Example 2

Input
source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []
Output
2

# Example 3

Input
source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]
Output
0

Constraints

n == source.length == target.length
1 <= n <= 10^5
1 <= source[i], target[i] <= 10^5
0 <= allowedSwaps.length <= 10^5
allowedSwaps[i].length == 2
0 <= ai, bi <= n - 1
ai != bi

Related LeetCode Problems

Practice more problems similar to Minimize Hamming Distance After Swap Operations.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.