Maximum XOR

Posted: 8 Dec, 2020
Difficulty: Hard

PROBLEM STATEMENT

Try Problem

You are given two arrays of non-negative integers say ‘arr1’ and ‘arr2’. Your task is to find the maximum value of ( ‘A’ xor ‘B’ ) where ‘A’ and ‘B’ are any elements from ‘arr1’ and ‘arr2’ respectively and ‘xor’ represents the bitwise xor operation.

Input Format:

The first line of the input contains an integer, 'T,’ denoting the number of test cases.

The first line of each test case contains two space-separated integers, 'N' and ‘M’ denoting the number of elements in the first and second array.

The second line of each test case contains 'N' space-separated integers denoting the elements of the array first array.

The last line of each test case contains 'M' space-separated integers denoting the elements of the array second array.

Output Format:

For each test case, print a single integer - the maximum possible xor among all possible pairs.

Print the output of each test case in a separate line.

Note :

You do not need to input or print anything, and it has already been taken care of. Just implement the given function.
Constraints:
1 <=  T  <= 5
1 <=  N, M <= 1000
0 <=  arr1[i], arr2[i]  <= 10 ^ 9

Where 'T' denotes the number of test cases, 'N', ‘M’ denotes the number of elements in the first array and second array, ‘arr1[i]', and ‘arr2[i]’ denotes the 'i-th' element of the first array and second array.

Time limit: 1 sec
Approach 1

SImply iterate over all possible pairs and find the maximum possible xor value.

 

Algorithm:

 

  • Let the given array be ‘arr1’ and ‘arr2’.
  • Declare a variable say ‘maxXor’. And initialize it with 0.
  • Run a loop form ‘i’ = 0 to length of ‘arr1’ - 1.
    • Run a loop from ‘j’ = 0 to length of ‘arr2’ - 1.
      • If ( ‘arr1[i]’ xor ‘arr2[j]’ ) > maxXor, then update ‘maxXor’ , i.e. do ‘maxXor’ = ( ‘arr1[i]’ xor ‘arr2[j]’ ).
  • Return ‘maxXor’.
Try Problem