Find XOR Sum of All Pairs Bitwise AND - Problem

The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.

For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.

You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.

Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.

Return the XOR sum of the aforementioned list.

Input & Output

Example 1 — Basic Case
$ Input: arr1 = [1,2], arr2 = [3,4,5]
Output: 2
💡 Note: All pairs: (1&3)=1, (1&4)=0, (1&5)=1, (2&3)=2, (2&4)=0, (2&5)=0. XOR sum: 1⊕0⊕1⊕2⊕0⊕0 = 2
Example 2 — Single Elements
$ Input: arr1 = [12], arr2 = [4]
Output: 4
💡 Note: Only one pair: 12 & 4 = 4. XOR sum of [4] = 4
Example 3 — All Zero Results
$ Input: arr1 = [1], arr2 = [2,4]
Output: 0
💡 Note: Pairs: (1&2)=0, (1&4)=0. XOR sum: 0⊕0 = 0

Constraints

  • 1 ≤ arr1.length, arr2.length ≤ 105
  • 0 ≤ arr1[i], arr2[j] ≤ 109

Visualization

Tap to expand
XOR Sum of All Pairs Bitwise AND INPUT arr1 = [1, 2] 1 2 arr2 = [3, 4, 5] 3 4 5 All AND Pairs: 1 AND 3 = 1 1 AND 4 = 0 1 AND 5 = 1 2 AND 3 = 2 2 AND 4 = 0 2 AND 5 = 0 Results: [1,0,1,2,0,0] XOR all: 1^0^1^2^0^0 = 2 ALGORITHM STEPS 1 Key Property (a AND b) XOR (a AND c) = a AND (b XOR c) 2 Distribute XOR XOR of all pairs = (XOR arr1) AND (XOR arr2) 3 Calculate XOR sums XOR(arr1) = 1 ^ 2 = 3 XOR(arr2) = 3 ^ 4 ^ 5 = 2 4 Final AND Result = 3 AND 2 3 = 011 (binary) 2 = 010 (binary) AND = 010 = 2 FINAL RESULT Output 2 Verification Brute Force: 1^0^1^2^0^0 = 2 Optimal O(n+m): (1^2) AND (3^4^5) = 3 AND 2 = 2 OK - Both match! VERIFIED Key Insight: The distributive property (a AND b) XOR (a AND c) = a AND (b XOR c) allows us to simplify O(n*m) pairs into just O(n+m) operations. Instead of computing all pairs, we XOR each array separately and AND the results. This elegant math trick reduces time complexity dramatically! TutorialsPoint - Find XOR Sum of All Pairs Bitwise AND | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
18.5K Views
Medium Frequency
~25 min Avg. Time
856 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