#2425
Bitwise XOR of All Pairings
MediumArrayBit ManipulationBrainteaserBit ManipulationCounting Frequencies
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(n) | O(n + m) |
💡
Intuition
Time O(n + m)Space O(n + m)
Instead of generating all pairings, we can leverage the properties of XOR and the counts of each number. Each number in nums1 contributes to the final result based on how many times it pairs with numbers in nums2 and vice versa.
⚙️
Algorithm
3 steps- 1Step 1: Count the occurrences of each number in nums1 and nums2.
- 2Step 2: For each unique number in nums1, calculate its contribution to the final XOR based on its count in nums2 and vice versa.
- 3Step 3: XOR all contributions together to get the final result.
solution.py16 lines
1# Full working Python code
2from collections import Counter
3
4def xor_all_pairings(nums1, nums2):
5 count1 = Counter(nums1)
6 count2 = Counter(nums2)
7 result = 0
8
9 for num in count1:
10 for num2 in count2:
11 if (count1[num] * count2[num2]) % 2 == 1:
12 result ^= (num ^ num2)
13 return result
14
15# Example usage
16print(xor_all_pairings([2, 1, 3], [10, 2, 5, 0]))ℹ
Complexity note: The time complexity is O(n + m) because we iterate through both arrays to count occurrences and then through the unique keys in the counts. The space complexity is O(n + m) for storing the counts.
- 1The XOR operation is commutative and associative, meaning the order of operations does not matter.
- 2Each number's contribution to the final XOR depends on how many times it is paired with other numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.