Imagine you have two arrays of the same length - source and target - and you want to make them as similar as possible! ๐ฏ
You're given a set of allowed swap operations that let you swap elements at specific pairs of indices in the source array. The catch? You can perform these swaps multiple times and in any order!
Your goal is to minimize the Hamming distance - the number of positions where the arrays differ. Think of it as a puzzle where you need to rearrange pieces optimally to match a target pattern.
Example: If source = [1,2,3,4] and target = [2,1,4,5], and you can swap positions (0,1) and (2,3), you could swap elements at indices 0 and 1 to get [2,1,3,4], reducing differences from 4 positions to just 2!
Input & Output
Visualization
Time & Space Complexity
Where m is number of allowed swaps and n is array length. We explore exponentially many swap combinations.
Space for storing current array state and recursion stack
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