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.
💡 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.
Minimize Hamming Distance After Swap Operations — Solution
The key insight is that indices connected by allowed swaps form components where elements can be freely rearranged. Use Union-Find to identify these components, then greedily match elements within each group. Time: O(m × α(n) + n), Space: O(n)
Common Approaches
✓
Brute Force - Try All Swap Combinations
⏱️ Time: O(2^m × n)
Space: O(n)
This approach tries all possible combinations of swaps to find the arrangement that minimizes Hamming distance. It explores every reachable state of the source array through the allowed swap operations.
Union-Find (Optimal Solution)
⏱️ Time: O(m × α(n) + n)
Space: O(n)
Use Union-Find to identify connected components of indices that can be swapped. Within each component, greedily match as many elements as possible between source and target arrays.
Brute Force - Try All Swap Combinations — Algorithm Steps
Generate all possible swap combinations
Apply swaps to create different arrangements
Calculate Hamming distance for each arrangement
Return the minimum distance found
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Original Arrays
Compare source and target arrays
2
Try Swaps
Apply different combinations of allowed swaps
3
Find Minimum
Track the arrangement with lowest Hamming distance
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int calculateHamming(int* arr1, int* arr2, int len) {
int count = 0;
for (int i = 0; i < len; i++) {
if (arr1[i] != arr2[i]) count++;
}
return count;
}
void applySwaps(int* arr, int* result, int n, int** swapsToApply, int* swapIndices, int numSwaps) {
memcpy(result, arr, n * sizeof(int));
for (int k = 0; k < numSwaps; k++) {
int idx = swapIndices[k];
int i = swapsToApply[idx][0];
int j = swapsToApply[idx][1];
int temp = result[i];
result[i] = result[j];
result[j] = temp;
}
}
void generateCombinations(int n, int r, int start, int* current, int currentSize, int** results, int* resultCount) {
if (currentSize == r) {
for (int i = 0; i < r; i++) {
results[*resultCount][i] = current[i];
}
(*resultCount)++;
return;
}
for (int i = start; i < n; i++) {
current[currentSize] = i;
generateCombinations(n, r, i + 1, current, currentSize + 1, results, resultCount);
}
}
int solution(int* source, int* target, int n, int** allowedSwaps, int swapCount) {
int minDistance = calculateHamming(source, target, n);
// Try all possible combinations of swaps
for (int r = 1; r <= swapCount; r++) {
int maxCombinations = 1;
for (int i = 0; i < r; i++) {
maxCombinations *= (swapCount - i);
maxCombinations /= (i + 1);
}
int** combinations = (int**)malloc(maxCombinations * sizeof(int*));
for (int i = 0; i < maxCombinations; i++) {
combinations[i] = (int*)malloc(r * sizeof(int));
}
int* current = (int*)malloc(r * sizeof(int));
int resultCount = 0;
generateCombinations(swapCount, r, 0, current, 0, combinations, &resultCount);
for (int c = 0; c < resultCount; c++) {
int* modified = (int*)malloc(n * sizeof(int));
applySwaps(source, modified, n, allowedSwaps, combinations[c], r);
int distance = calculateHamming(modified, target, n);
if (distance < minDistance) {
minDistance = distance;
}
free(modified);
}
for (int i = 0; i < maxCombinations; i++) {
free(combinations[i]);
}
free(combinations);
free(current);
}
return minDistance;
}
int main() {
char line[1000];
fgets(line, sizeof(line), stdin);
int source[100];
int sourceSize;
parseArray(line, source, &sourceSize);
fgets(line, sizeof(line), stdin);
int target[100];
int targetSize;
parseArray(line, target, &targetSize);
fgets(line, sizeof(line), stdin);
int** allowedSwaps = (int**)malloc(50 * sizeof(int*));
int swapCount = 0;
if (strcmp(line, "[]\n") != 0) {
char* p = line;
while (*p) {
if (*p == '[' && *(p+1) != ']') {
p++;
int nums[2];
int numCount = 0;
while (*p && *p != ']' && numCount < 2) {
while (*p == ' ' || *p == ',') p++;
if (*p >= '0' && *p <= '9') {
nums[numCount++] = (int)strtol(p, &p, 10);
} else {
p++;
}
}
if (numCount == 2) {
allowedSwaps[swapCount] = (int*)malloc(2 * sizeof(int));
allowedSwaps[swapCount][0] = nums[0];
allowedSwaps[swapCount][1] = nums[1];
swapCount++;
}
} else {
p++;
}
}
}
int result = solution(source, target, sourceSize, allowedSwaps, swapCount);
printf("%d\n", result);
for (int i = 0; i < swapCount; i++) {
free(allowedSwaps[i]);
}
free(allowedSwaps);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(2^m × n)
2^m possible swap combinations times n to calculate distance
n
2n
✓ Linear Growth
Space Complexity
O(n)
Space to store array copies during exploration
n
2n
⚡ Linearithmic Space
28.4K Views
MediumFrequency
~25 minAvg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.