You are given the two integers 'N' and 'X'. Your task is to find an array 'P' such that:
'P' is a permutation of (0, 1, 2, ..., 2 ^ (N - 1)).
The first element of the array 'P' is 'X', i.e., P[0] = X.
Adjacent elements of 'P' (i.e., P[i] and P[i + 1]) differ by only 1 bit in their binary representation.
The first and the last element (i.e., P[0] and P[2^N -1]) are also considered as adjacent elements.
Note:
For N = 2, [0,1,2,3], [0,2,3,1], [1,2,3,0] are some of the valid permutations but [0,0,1,2], [1,2,3,4], [1,1,1,3] are not.
It is guaranteed that an array 'P' always exits with the given requirements.
The first line contains an integer 'T', which denotes the number of test cases or queries to be run. Then, the 'T' test cases follow.
The first line and only line of each test case contain 2 positive integers, 'N' and 'X', as described in the problem statement.
Output Format:
For each test case, print in a new line an array 'P' of size 2^N denoting a permutation of (0,1, ..., 2^N -1) with the given requirements, as described in the problem statement.
If there exist multiple permutations satisfying the above conditions, then you can print any.
Output for each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N <= 13
0 <= X < 2^N
Time Limit: 1 sec
1
1 1
1 0
The binary representation of the array [1,0] is also (1,0) in which adjacent elements differ by only 1 bit.
1
2 0
0 1 3 2
Think of using n-bit gray code.
The idea here is to use an algorithm to generate n-bit gray code. Recall that, n-bit gray code sequence is a sequence of 2^n numbers from 0 to 2^n -1 such that it starts with 0 and two successive values differ only in 1 bit. Let say this sequence to be arrGray. More information on how to generate n-bit gray code can be found here: Wikipedia.
We have to find the index of X (which is given in the problem) in sequence arrGray. Let say we have found X at the i-th index of arrGray. Then simply, our required array P can be arrGray[i:] + arrGray[:i], which means P is the Concatenation of the two subarrays of arrGray. The first one is from i-th index to the last, and the second, from the 0-th index to the (i-1)th index.
O(2 ^ N), where N is the positive number given in the problem.
We are creating an n-bit Gray code sequence whose size is 2 ^ N. So, we have to run a loop till 2 ^ N for the sequence. Hence, the overall time complexity is O(2 ^ N).
O(2 ^ N), where N is the positive number given in the problem.
We are using an array of size 2 ^ N for storing both the n-bit gray code sequence and the final answer. Hence, the space complexity is O(2 ^ N).