Last Updated: 1 Mar, 2021

Ninja And XOR

Easy
Asked in companies
AdobeSnapdeal Ltd.

Problem statement

Ninja has been given an array/list ‘ARR’ having ‘N’ positive integers. Ninja wants to reconstruct the ‘ARR’ such that the newly formed array contains the XOR of consecutive elements in the ‘ARR’.

For Example: For ‘ARR’ = [1, 2, 3, 4, 5] the reconstructed ‘ARR’ will be [3, 1, 7, 1, 5].

1. The element at index  0 in the new ‘ARR’ is 3 because ‘ARR[0]’ ^ ‘ARR[1]’ is 1 ^ 2 which is equal to 3.

2. The element at index  1 in the new ‘ARR’ is 1 because ‘ARR[1]’ ^ ‘ARR[2]’ is 2 ^ 3 which is equal to 1.

3. The element at index  2 in the new ‘ARR’ is 7 because ‘ARR[2]’ ^ ‘ARR[3]’ is 3 ^ 4 which is equal to 7.

4. The element at index  3 in the new ‘ARR’ is 1 because ‘ARR[3]’ ^ ‘ARR[4]’ is 4 ^ 5 which is equal to 1.

5. The element at index  4 in the new ‘ARR’ is 5 because there is no element in the right of ‘ARR[4]’ so it will remain as it is in the new ‘ARR’. 

Note:

As Ninja is busy with some other task, so he asks you for help. Can you help Ninja to reconstruct the ‘ARR’?
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case contains a single integer 'N' denoting the number of elements in the 'ARR'.

The second line of each test case contains 'N' single space-separated integers, denoting the element in the 'ARR'.
Output Format:
For each test case, print a single line containing 'N' space-separated integers denoting the elements of reconstructed ‘ARR’.

The output of each test case will be printed in a separate line.

Note:

You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 10 ^ 4
1 <= ARR[i] <= 10 ^ 7

Where 'T' is the number of test cases, 'N' denotes the number of elements in the 'ARR’ and 'ARR[i]' denotes the element at the ‘i’th index, respectively.

Time Limit: 1 sec 

Approaches

01 Approach

The idea behind this approach is to simply iterate the ‘ARR’ and do the XOR operation for each consecutive element.

 

Here is the complete Algorithm:

  • Iterate the ‘ARR’ for ‘N-1’ times and for each element at index ‘i’ do the following:
    • Do the XOR operation on ‘ARR[i]’ and ‘ARR[i+1]’ and update the result at ‘ARR[i]’ as ‘ARR[i]’ = ‘ARR[i]’ ^ ‘ARR[i+1]’.
  • Finally, return ‘ARR