Program to find XOR sum of all pairs bitwise AND in Python


Suppose we have two arrays arr1 and arr2. The XOR sum of a list is the bitwise XOR of all of its elements. If the list has only one element, then its XOR sum will be the element itself. Now, consider the list has the result of arr1[i] AND arr2[j] (bitwise AND) for every index pair (i, j) where 0 <= i < length of arr1 and 0 <= j < length of arr2. We have to find the XOR sum of that list.

So, if the input is like arr1 = [5,3,4] arr2 = [2,6], then the output will be 0 because the list is [5 AND 2, 5 AND 6, 3 AND 2, 3 AND 6, 4 AND 2, 4 AND 6] = [0, 4, 2, 2, 0, 4], now XOR sum is [0 XOR 4 XOR 2 XOR 2 XOR 0 XOR 4] = 0

To solve this, we will follow these steps −

  • xor1 := 0

  • xor2 := 0

  • for each a in arr1, do

    • xor1 := xor1 XOR a

  • for each a in arr2, do

    • xor2 := xor2 XOR a

  • return xor1 AND xor2

Example

Let us see the following implementation to get better understanding

def solve(arr1, arr2):
   xor1 = 0
   xor2 = 0
   for a in arr1:
      xor1 ^= a
   for a in arr2:
      xor2 ^= a
   return xor1 & xor2

arr1 = [5,3,4]
arr2 = [2,6]
print(solve(arr1, arr2))

Input

[5,3,4], [2,6]

Output

0

Updated on: 08-Oct-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements