Minimum XOR Sum of Two Arrays - Problem

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

example_1.py — Python
$ Input: nums1 = [1,2], nums2 = [2,3]
› Output: 1
šŸ’” Note: Rearrange nums2 to [3,2]. XOR sum = (1^3) + (2^2) = 2 + 0 = 2. Alternative: [2,3] gives (1^2) + (2^3) = 3 + 1 = 4. Minimum is 1 when we use [3,2].
example_2.py — Python
$ Input: nums1 = [1,0,3], nums2 = [5,3,4]
› Output: 8
šŸ’” Note: Optimal arrangement: nums2 = [5,4,3]. XOR sum = (1^5) + (0^4) + (3^3) = 4 + 4 + 0 = 8. The key insight is pairing 3 with 3 to get 0.
example_3.py — Python
$ Input: nums1 = [1], nums2 = [1]
› Output: 0
šŸ’” Note: Only one element in each array. XOR sum = 1^1 = 0, which is the minimum possible XOR value.

Visualization

Tap to expand
Minimum XOR Sum: Assignment Strategy12Fixed Seats (nums1)23Flexible Guests (nums2)Assign to minimize XORDP State: mask = 01 (guest 2 assigned)Current cost: 1 XOR 2 = 3Next: try assigning guest 3 to seat 2Optimal Assignment: [3,2] → XOR sum = 1(1 XOR 3) + (2 XOR 2) = 2 + 0 = 2
Understanding the Visualization
1
Problem Setup
We have fixed seats (nums1) and flexible guests (nums2)
2
DP States
Each bitmask represents which guests have been seated
3
Transitions
For each empty seat, try all remaining guests
4
Optimal Solution
Find minimum cost when all guests are seated
Key Takeaway
šŸŽÆ Key Insight: Use bitmask DP where each bit represents assignment status, allowing efficient exploration of all O(2ⁿ) possible partial assignments while avoiding redundant computations.

Time & Space Complexity

Time Complexity
ā±ļø
O(n² Ɨ 2ⁿ)

For each of 2ⁿ possible masks, we consider n positions and n choices

n
2n
⚠ Quadratic Growth
Space Complexity
O(2ⁿ)

DP array to store results for each possible mask

n
2n
āœ“ Linear Space

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
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
28.0K Views
Medium Frequency
~25 min Avg. Time
850 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