


You're given an array ARR[] of size N, where every element belongs to the range 0 to N-1. Your task is to rearrange the given array so that ARR[i] becomes ARR[ARR[i]] and make sure that this task is done with O(1) extra space.
The first line contains an integer 'T', denoting the number of test cases. The 'T' test cases follow.
The first line of each test case contains an integer N, the size of the array.
The second line of each test case contains N space-separated integers.
Output Format :
For each test case, print the rearranged array as described in the problem statement.
Note :
You don’t need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10^2
1 <= N <= 10^4
0 <= ARR[i] <= N-1
Where 'ARR[i]' is 'ith' element of ARR.
Time Limit : 1 sec
1
4
0 1 2 3
0 1 2 3
We can see that ARR[ARR[0]] i.e ARR[0] is 0, hence ARR[0] in the output array will be 0. Also, ARR[ARR[1]] i.e ARR[1] is1, hence ARR[1] in the output array will be 1. Similarly, ARR[ARR[2]] i.e ARR[2] is 2, hence ARR[2] in the output array will be 2. Finally, ARR[ARR[3]] i.e ARR[3] is 3, hence ARR[3] in the output array will be 3.
1
4
3 2 0 1
1 0 3 2
We can see that ARR[ARR[0]] i.e ARR[3] is 1, hence ARR[0] in the output array will be 1. Also, ARR[ARR[1]] i.e ARR[2] is 0, hence ARR[1] in the output array will be 0. Similarly, ARR[ARR[2]] i.e ARR[0] is 3, hence ARR[2] in the output array will be 3. Finally, ARR[ARR[3]] i.e ARR[1] is 2, hence ARR[3] in the output array will be 2.
Can you extract more than one entry from the given numbers?
As we are not allowed to use any extra space, we need to find an array element that can store two values at the same time. To do so, we increment every element at the ith index by (arr[arr[i]]%N)*N. Now after this increment every element is now holding two values, the old value and the new value. The old value can be obtained by arr[i]%N and the new value can be obtained by arr[i]/N. Let us understand how this is achieved.
Now let’s see how to reach the solution to our problem.
O(N), where N is the size of the array.
Since only one traversal of array is needed.
O(1).
As we are using extra constant memory.