You are given two integer arrays nums1 and nums2, both of length n. Your task is to find an optimal pairing strategy that minimizes the total XOR sum.
The XOR sum is calculated as: (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n-1] XOR nums2[n-1])
For example: If nums1 = [1,2,3] and nums2 = [3,2,1], the XOR sum equals (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4
You can rearrange the elements of nums2 in any order to minimize this sum. Your goal is to find the arrangement that produces the smallest possible XOR sum.
Key insight: XOR operations have unique properties that can be exploited - when two identical numbers are XORed, the result is 0, and XOR values tend to be smaller when the binary representations of numbers are similar.
Input & Output
Visualization
Time & Space Complexity
For each of 2āæ possible masks, we consider n positions and n choices
DP array to store results for each possible mask
Constraints
- n == nums1.length
- n == nums2.length
- 1 ⤠n ⤠14
- 0 ⤠nums1[i], nums2[i] ⤠107
- Note: The constraint n ⤠14 makes bitmask DP feasible since 214 = 16,384 is manageable