Minimum XOR Sum of Two Arrays - Problem

You are given two integer arrays nums1 and nums2 of length n.

The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed).

For example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4.

Rearrange the elements of nums2 such that the resulting XOR sum is minimized.

Return the XOR sum after the rearrangement.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,2], nums2 = [2,3]
Output: 2
💡 Note: Rearrange nums2 to [3,2]. XOR sum = (1^3) + (2^2) = 2 + 0 = 2, which is minimum
Example 2 — Three Elements
$ Input: nums1 = [1,2,3], nums2 = [1,2,3]
Output: 0
💡 Note: Keep nums2 as [1,2,3]. XOR sum = (1^1) + (2^2) + (3^3) = 0 + 0 + 0 = 0
Example 3 — No Perfect Match
$ Input: nums1 = [1,0,3], nums2 = [5,3,4]
Output: 8
💡 Note: Rearrange nums2 to [5,4,3]. XOR sum = (1^5) + (0^4) + (3^3) = 4 + 4 + 0 = 8

Constraints

  • n == nums1.length
  • n == nums2.length
  • 1 ≤ n ≤ 14
  • 0 ≤ nums1[i], nums2[i] ≤ 107

Visualization

Tap to expand
Minimum XOR Sum: Find Optimal Arrangementnums1 (fixed)123nums2 (original)321XOR Sum = (1^3) + (2^2) + (3^1) = 2 + 0 + 2 = 4nums2 (optimal)123XOR Sum = (1^1) + (2^2) + (3^3) = 0 + 0 + 0 = 0Minimum XOR Sum: 0Found by trying all possible arrangements of nums2
Understanding the Visualization
1
Input Arrays
Two arrays nums1 and nums2 of equal length
2
Rearrange nums2
Find optimal permutation of nums2 to minimize XOR sum
3
Calculate Result
Sum of XOR operations between corresponding elements
Key Takeaway
🎯 Key Insight: This is an assignment problem where we must find the optimal one-to-one pairing between elements to minimize total cost
Asked in
Google 15 Microsoft 12 Amazon 8
18.5K Views
Medium Frequency
~25 min Avg. Time
450 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