You are given an array of N integers. Your task is to rearrange the elements of the array such that the total XOR sum of all adjacent elements is maximized.
The XOR sum is defined as follows. For an array a of size N, compute:
F = (a[1] ⊕ a[0]) + (a[2] ⊕ a[1]) + ... + (a[N-1] ⊕ a[N-2]) where ⊕ denotes the bitwise XOR operator.
Your goal is to output a permutation of the original array that results in the maximum possible value of F.
Note :You do not need to print anything; it has already been taken care of. Just implement the given function.
The first line of input contains T, the number of test cases.
For each test case, the first line contains a number ‘N’, which is the size of the array.
The next line contains N space-separated integers, that denote the values of the elements in the array.
Output Format :
The output of each test case contains ‘N’ integers, denoting the order in which the elements should be kept such that the result is largest.
1 <= T <= 5
1 <= N <= 3000
1 <= data <= 10^5
where ‘T’ is the number of test cases, N is the number of elements in the array.
Time Limit : 1sec
1
3
5 4 6
6 5 4
This is because ( 4 ^ (5 ^ 6) ) is the greatest value when compared to any other permutations.
1
2
2 3
2 3
Does sorting the elements help?
To maximize the sum of XOR values between adjacent elements, we observe the following:
Algorithm:
O(N * log(N)), where N is the number of elements in the array.
Since we are sorting the array and then traversing the array to get the final output, the net time complexity will be O(N * log(N)) + O(N) = O(N * log(N)).
O(1)
Since we did not use any extra space.