Bitwise XOR of All Pairings - Problem

Imagine you have two arrays of non-negative integers, nums1 and nums2. Your task is to create all possible pairs where you take one number from nums1 and one number from nums2, then calculate the bitwise XOR of each pair.

For example, if nums1 = [2, 1] and nums2 = [1, 3], you would create pairs: (2, 1), (2, 3), (1, 1), and (1, 3). The XOR values would be [3, 1, 0, 2].

Finally, you need to return the XOR of all these XOR values. This might seem like you need to compute all pairs explicitly, but there's a clever mathematical pattern that can solve this much more efficiently!

Can you find the pattern that avoids computing all O(m×n) pairs?

Input & Output

example_1.py — Basic Case
$ Input: nums1 = [2,1], nums2 = [1,3]
Output: 0
💡 Note: All pairings: (2,1)→3, (2,3)→1, (1,1)→0, (1,3)→2. Final XOR: 3⊕1⊕0⊕2 = 0. Using the optimal approach: both arrays have even-length counterparts, so all contributions cancel out.
example_2.py — Single Elements
$ Input: nums1 = [1], nums2 = [6]
Output: 7
💡 Note: Only one pairing: (1,6)→7. Since nums2 has length 1 (odd), nums1's XOR (which is 1) contributes. Since nums1 has length 1 (odd), nums2's XOR (which is 6) contributes. Result: 1⊕6 = 7.
example_3.py — Mixed Lengths
$ Input: nums1 = [1,2,3], nums2 = [4,5]
Output: 4
💡 Note: nums1 XOR = 1⊕2⊕3 = 0, nums2 XOR = 4⊕5 = 1. Since len(nums2)=2 is even, nums1's contribution cancels. Since len(nums1)=3 is odd, nums2's contribution (1) remains. Result: 1.

Visualization

Tap to expand
The XOR Cancellation PatternAAppears 3 timesBAppears 2 timesCAppears 4 timesODDSURVIVESEVENCANCELSEVENCANCELSFinal ResultOnly A contributes!
Understanding the Visualization
1
Count the Dances
Each nums1 element dances len(nums2) times, each nums2 element dances len(nums1) times
2
Find the Survivors
Only dancers with odd performance counts contribute to the final result
3
Combine Contributions
XOR the surviving group contributions together
Key Takeaway
🎯 Key Insight: XOR's self-canceling property (x ⊕ x = 0) means we only need to count occurrences and track which elements appear an odd number of times!

Time & Space Complexity

Time Complexity
⏱️
O(m × n)

We need to generate all m × n pairs and compute XOR for each

n
2n
Linear Growth
Space Complexity
O(1)

Only using a constant amount of extra space for the result variable

n
2n
Linear Space

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 105
  • 0 ≤ nums1[i], nums2[j] ≤ 109
  • Arrays contain only non-negative integers
Asked in
Google 45 Meta 35 Microsoft 28 Amazon 22
42.0K Views
Medium Frequency
~18 min Avg. Time
1.9K 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