Minimum XOR Sum of Two Arrays

Hard
#1715Time: O(n * n!) - There are `n!` possible permutations of `nums2`. For each permutation, we take O(n) time to calculate the XOR sum. Thus, the total time complexity is `n * n!`.Space: O(n) - The space complexity is determined by the depth of the recursion stack for generating permutations, which is `n`.1 company

Prompt

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.

 

Example 1:

nums2

Example 2:

nums2

 

Constraints:

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

Approaches

2 approaches with complexity analysis and trade-offs.

The most straightforward way to solve the problem is to try every possible arrangement of nums2. Since we can rearrange nums2 in any way, this corresponds to finding the best permutation of nums2 that, when paired element-wise with nums1, yields the minimum possible XOR sum. We can generate all n! permutations of nums2, calculate the XOR sum for each, and find the minimum among them.

Algorithm

  • The core idea is to generate every possible arrangement (permutation) of the nums2 array.
  • For each permutation of nums2, we calculate the XOR sum by pairing nums1[i] with the i-th element of the permuted nums2.
  • We maintain a global variable to keep track of the minimum XOR sum found so far across all permutations.
  • This can be implemented using a recursive backtracking function that generates all permutations.
  • The steps for the recursive function permute(index, current_nums2) are:
    • Base Case: If index reaches the length of the array n, it means we have a full permutation. Calculate the XOR sum for this permutation and update the global minimum.
    • Recursive Step: Iterate a loop from i = index to n-1. In each iteration:
      • Swap current_nums2[index] with current_nums2[i] to place a new element at the current position.
      • Make a recursive call for the next position: permute(index + 1, current_nums2).
      • Backtrack by swapping current_nums2[index] and current_nums2[i] back to their original positions. This is crucial to explore all possible permutations correctly.

Walkthrough

This approach tackles the problem by exploring the entire search space of permutations. The problem asks to rearrange nums2 to minimize the XOR sum. A rearrangement of nums2 is simply a permutation. Therefore, we can systematically generate all permutations of nums2. For each generated permutation, we compute the XOR sum against the fixed nums1 array: (nums1[0] XOR p_nums2[0]) + (nums1[1] XOR p_nums2[1]) + .... We compare this sum with a running minimum and update it if the new sum is smaller. The final result is the minimum value found after checking all n! permutations.

class Solution {    int minXorSum = Integer.MAX_VALUE;        public int minimumXORSum(int[] nums1, int[] nums2) {        permute(nums1, nums2, 0);        return minXorSum;    }        private void permute(int[] nums1, int[] nums2, int index) {        if (index == nums1.length) {            int currentXorSum = 0;            for (int i = 0; i < nums1.length; i++) {                currentXorSum += nums1[i] ^ nums2[i];            }            minXorSum = Math.min(minXorSum, currentXorSum);            return;        }                for (int i = index; i < nums2.length; i++) {            swap(nums2, index, i);            permute(nums1, nums2, index + 1);            swap(nums2, index, i); // backtrack        }    }        private void swap(int[] nums, int i, int j) {        int temp = nums[i];        nums[i] = nums[j];        nums[j] = temp;    }}

Complexity

Time

O(n * n!) - There are `n!` possible permutations of `nums2`. For each permutation, we take O(n) time to calculate the XOR sum. Thus, the total time complexity is `n * n!`.

Space

O(n) - The space complexity is determined by the depth of the recursion stack for generating permutations, which is `n`.

Trade-offs

Pros

  • Conceptually simple and easy to understand.

  • Correct for very small values of n.

Cons

  • Extremely inefficient due to its factorial time complexity.

  • Will result in a 'Time Limit Exceeded' error on most platforms for the given constraints (n <= 14).

Solutions

class Solution {public  int minimumXORSum(int[] nums1, int[] nums2) {    int n = nums1.length;    int[][] f = new int[n + 1][1 << n];    for (var g : f) {      Arrays.fill(g, 1 << 30);    }    f[0][0] = 0;    for (int i = 1; i <= n; ++i) {      for (int j = 0; j < 1 << n; ++j) {        for (int k = 0; k < n; ++k) {          if ((j >> k & 1) == 1) {            f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] +                                            (nums1[i - 1] ^ nums2[k]));          }        }      }    }    return f[n][(1 << n) - 1];  }}

Video walkthrough

Newsletter

One sharp idea, every week

System design and interview prep — short enough to finish.

No spam. Unsubscribe anytime.

Practice

Same difficulty — related problems to reinforce the pattern.