Bitwise XOR of All Pairings

medium bit manipulation xor brainteaser

Problem

Given two arrays nums1 (length m) and nums2 (length n), form nums3 as the XOR of every pairing nums1[i] ^ nums2[j] — all m × n of them. Return the bitwise XOR of all numbers in nums3.

The trick: across those m × n XORs, each nums1[i] appears exactly n times and each nums2[j] appears exactly m times. Since v ^ v = 0, a value cancels when it is repeated an even number of times, and survives only when repeated an odd number of times.

Inputnums1 = [2,1,3], nums2 = [10,2,5,0]
Output13
m = 3 (odd) so nums2 survives; n = 4 (even) so nums1 cancels. Answer = 10 ^ 2 ^ 5 ^ 0 = 13.

def xorAllNums(nums1, nums2):
    m, n = len(nums1), len(nums2)
    ans = 0
    # each nums2[j] is paired with all m of nums1,
    # so it appears m times; keep it only if m is odd
    if m % 2 == 1:
        for v in nums2:
            ans ^= v
    # each nums1[i] appears n times; keep it only if n is odd
    if n % 2 == 1:
        for v in nums1:
            ans ^= v
    return ans
function xorAllNums(nums1, nums2) {
  const m = nums1.length, n = nums2.length;
  let ans = 0;
  // each nums2[j] is paired with all m of nums1,
  // so it appears m times; keep it only if m is odd
  if (m % 2 === 1) {
    for (const v of nums2) ans ^= v;
  }
  // each nums1[i] appears n times; keep it only if n is odd
  if (n % 2 === 1) {
    for (const v of nums1) ans ^= v;
  }
  return ans;
}
int xorAllNums(int[] nums1, int[] nums2) {
    int m = nums1.length, n = nums2.length;
    int ans = 0;
    // each nums2[j] is paired with all m of nums1,
    // so it appears m times; keep it only if m is odd
    if (m % 2 == 1) {
        for (int v : nums2) ans ^= v;
    }
    // each nums1[i] appears n times; keep it only if n is odd
    if (n % 2 == 1) {
        for (int v : nums1) ans ^= v;
    }
    return ans;
}
int xorAllNums(vector<int>& nums1, vector<int>& nums2) {
    int m = nums1.size(), n = nums2.size();
    int ans = 0;
    // each nums2[j] is paired with all m of nums1,
    // so it appears m times; keep it only if m is odd
    if (m % 2 == 1) {
        for (int v : nums2) ans ^= v;
    }
    // each nums1[i] appears n times; keep it only if n is odd
    if (n % 2 == 1) {
        for (int v : nums1) ans ^= v;
    }
    return ans;
}
Time: O(m + n) Space: O(1)