Find XOR Sum of All Pairs Bitwise AND - Problem
The XOR Sum Challenge: Master bitwise operations in this fascinating problem!
You're given two arrays
1️⃣ Create all pairs: For every element
2️⃣ XOR everything: Take the XOR of all these AND results
Key insight: The XOR sum of a list is the bitwise XOR of all elements. For example, XOR sum of [1,2,3,4] = 1 ⊕ 2 ⊕ 3 ⊕ 4 = 4
Example: If arr1 = [1,2] and arr2 = [3,4]
• Pairs: (1&3)=1, (1&4)=0, (2&3)=2, (2&4)=0
• Result: 1 ⊕ 0 ⊕ 2 ⊕ 0 = 3
You're given two arrays
arr1 and arr2 containing non-negative integers. Your mission is to:1️⃣ Create all pairs: For every element
arr1[i] and arr2[j], compute their bitwise AND (arr1[i] & arr2[j])2️⃣ XOR everything: Take the XOR of all these AND results
Key insight: The XOR sum of a list is the bitwise XOR of all elements. For example, XOR sum of [1,2,3,4] = 1 ⊕ 2 ⊕ 3 ⊕ 4 = 4
Example: If arr1 = [1,2] and arr2 = [3,4]
• Pairs: (1&3)=1, (1&4)=0, (2&3)=2, (2&4)=0
• Result: 1 ⊕ 0 ⊕ 2 ⊕ 0 = 3
Input & Output
example_1.py — Basic Example
$
Input:
arr1 = [1,2], arr2 = [3,4]
›
Output:
3
💡 Note:
All pairs: (1&3)=1, (1&4)=0, (2&3)=2, (2&4)=0. XOR sum: 1⊕0⊕2⊕0 = 3. Using optimal approach: (1⊕2)&(3⊕4) = 3&7 = 3
example_2.py — Single Elements
$
Input:
arr1 = [12], arr2 = [4]
›
Output:
4
💡 Note:
Only one pair: (12&4). Binary: 1100&0100 = 0100 = 4. XOR sum of [4] is just 4. Optimal: (12)&(4) = 4
example_3.py — Zero Result
$
Input:
arr1 = [1,3], arr2 = [2,4]
›
Output:
0
💡 Note:
All pairs: (1&2)=0, (1&4)=0, (3&2)=2, (3&4)=0. XOR sum: 0⊕0⊕2⊕0 = 2. Wait... let me recalculate: (1⊕3)&(2⊕4) = 2&6 = 2
Visualization
Tap to expand
Understanding the Visualization
1
XOR Magic
XOR all spotlights in each row separately
2
AND Result
AND the two XOR results to get the final effect
3
Mathematical Proof
This works due to the distributive property of bitwise operations
Key Takeaway
🎯 Key Insight: The mathematical property (a₁⊕a₂⊕...)&(b₁⊕b₂⊕...) gives the same result as computing all pairs individually, but in O(n+m) time instead of O(n×m)!
Time & Space Complexity
Time Complexity
O(n + m)
We iterate through each array once for each of 32 bit positions, giving us O(32(n+m)) = O(n+m)
✓ Linear Growth
Space Complexity
O(1)
Only using constant extra space for counters and result
✓ Linear Space
Constraints
- 1 ≤ arr1.length, arr2.length ≤ 105
- 0 ≤ arr1[i], arr2[j] ≤ 109
- Time limit: 1 second per test case
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code