Intuition
Every allowed swap is reversible, so the set of permutations reachable on source is exactly the orbit under the swap relation. Enumerate every reachable permutation and pick the one closest to target. This is exponential but illustrates what's being asked.
Explanation
Approach
- BFS or recursive expansion over permutations of
source, swapping along edges inallowedSwaps. - For each reachable permutation, count Hamming distance to
target. - Return the minimum.
Complexity
- Time:
O(n! · n)worst case — only practical for tinyn. - Space:
O(n!)to memoise visited states.
Implementation
import java.util.*;
class Solution {
public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {
int n = source.length;
Set<String> seen = new HashSet<>();
String init = Arrays.toString(source);
seen.add(init);
Queue<int[]> queue = new LinkedList<>();
queue.offer(source.clone());
int best = 0;
for (int i = 0; i < n; i++) {
if (source[i] != target[i]) best++;
}
while (!queue.isEmpty()) {
int[] cur = queue.poll();
int ham = 0;
for (int i = 0; i < n; i++) {
if (cur[i] != target[i]) ham++;
}
best = Math.min(best, ham);
for (int[] swap : allowedSwaps) {
int[] nxt = cur.clone();
int tmp = nxt[swap[0]];
nxt[swap[0]] = nxt[swap[1]];
nxt[swap[1]] = tmp;
String key = Arrays.toString(nxt);
if (!seen.contains(key)) {
seen.add(key);
queue.offer(nxt);
}
}
}
return best;
}
}