Minimize Hamming Distance After Swap Operations - Problem

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.

Input & Output

Example 1 — Basic Swapping
$ Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]
Output: 1
💡 Note: We can swap indices 0 and 1 to get [2,1,3,4]. This matches target at positions 0,1,2 but differs at position 3 (4 vs 5), giving Hamming distance = 1.
Example 2 — No Beneficial Swaps
$ Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = [[0,1],[2,3]]
Output: 2
💡 Note: Even with swaps [0,1] or [2,3], we cannot make source match target better than the original 2 mismatches at positions 1 and 2.
Example 3 — No Swaps Allowed
$ Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = []
Output: 4
💡 Note: No swaps allowed, so Hamming distance is simply the count of differing positions: 4 out of 5 positions differ.

Constraints

  • n == source.length == target.length
  • 1 ≤ n ≤ 105
  • 1 ≤ source[i], target[i] ≤ 105
  • 0 ≤ allowedSwaps.length ≤ 105
  • allowedSwaps[i].length == 2
  • 0 ≤ ai, bi ≤ n - 1
  • ai ≠ bi

Visualization

Tap to expand
Minimize Hamming Distance After Swap OperationsInput:source = [1,2,3,4]target = [2,1,4,5]allowedSwaps = [[0,1],[2,3]]Process:Component 1: Indices [0,1]Source values: [1,2]Target values: [2,1]Perfect match possible ✓Component 2: Indices [2,3]Source values: [3,4]Target values: [4,5]1 match (4), 1 mismatch ✗Result:Optimal arrangement: [2,1,3,4]Minimum Hamming Distance: 1Only position 3 differs:source[3]=4, target[3]=5
Understanding the Visualization
1
Input
Two arrays and allowed swap pairs
2
Process
Group indices by connectivity and optimize matches
3
Output
Minimum possible Hamming distance
Key Takeaway
🎯 Key Insight: Connected indices through swaps form components where optimal matching can be achieved independently
Asked in
Google 45 Microsoft 38 Amazon 32 Facebook 28
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen