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 of Two Arrays INPUT nums1 1 2 nums2 2 3 Input Values: nums1 = [1, 2] nums2 = [2, 3] n = 2 Goal: Minimize XOR sum ALGORITHM STEPS 1 Calculate XOR pairs Compute all possible XORs 1^2=3 1^3=2 2^2=0 2^3=1 2 Greedy Selection Pick min XOR at each step 3 Try arrangements [2,3] or [3,2] for nums2 4 Compare sums Option A: 3+1=4 Option B: 2+0=2 Best: [3,2] = 2 FINAL RESULT Optimal Arrangement nums1: 1 2 nums2 (rearranged): 3 2 XOR XOR 2 0 2 + 0 = 2 Output: 2 Key Insight: The greedy approach tries to minimize each XOR pair. For small arrays, we can evaluate all permutations. Pairing 1 with 3 gives XOR=2, and 2 with 2 gives XOR=0. Total: 2+0=2 (minimum possible). TutorialsPoint - Minimum XOR Sum of Two Arrays | Greedy Approach
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