Problem Description
Given two 0-indexed arrays, nums1 and nums2, containing non-negative integers, we consider an array nums3 that contains the bitwise XOR of all pairings (every combination where one element is taken from nums1 and one from nums2). The task is to return the bitwise XOR of all numbers in nums3.
Key Insights
- Each element in nums1 is paired with every element in nums2 exactly once.
- In the overall XOR, any number that appears an even number of times cancels itself.
- Every element in nums1 is used |nums2| times; thus, if |nums2| is even, the contributions of nums1 vanish.
- Similarly, every element in nums2 is used |nums1| times; if |nums1| is even, the contributions of nums2 vanish.
- If |nums2| is odd, then the XOR of all elements in nums1 remains. Similarly, if |nums1| is odd, then the XOR of all elements in nums2 remains.
- The final answer is the XOR of these contributions.
Space and Time Complexity
Time Complexity: O(n + m), where n = length of nums1 and m = length of nums2.
Space Complexity: O(1) (ignoring input storage).
Solution
The solution leverages the cancellation property of XOR when an element appears an even number of times. For every x in nums1, note it appears |nums2| times in the overall XOR. Therefore, if |nums2| is odd, then the XOR of all values in nums1 persists; otherwise, they cancel out. The same reasoning applies to the elements in nums2 if |nums1| is odd. We then combine these results by taking the XOR of the two contributions. This approach avoids explicitly computing the pairwise XORs, achieving an efficient solution.