In an interview of a company the interviewer asked a question to the student that you are given a permutation ‘permArray’ of length ‘N’ (N is always even) which is filled with values 0 to N-1 such that permArray[i] = i. The student has to perform operations on the ‘permArray’ which are given below.
In one operation, you will create a new array ‘ARR’, and for each i:
1) If i % 2 == 0, then ARR[i] = permArray[i / 2].
2) If i % 2 == 1, then ARR[i] = permArray[N / 2 + (i - 1) / 2].
You will then assign ARR to 'permArray'.
The student has to find the minimum number of non-zero operations to make the ‘permArray’ return to its original state. Assuming yourselves as the student, solve the question given by the interviewer.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains an integer ‘N’, denoting the length of the permutation.
Output format :
For each test case, print the minimum number of non-zero operations to make the given array back to its original state.
Output for each test case is printed on 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 <= 10
2 <= N <= 10^5
N%2 = 0
Where ‘T’ represents the number of test cases, ‘N’ represents the length of the permutation ‘permArray’.
Time Limit: 1 sec
2
2
4
1
2
For the first test case,
Initially, the ‘permArray’ will look like [0, 1]. Then we will create a new array ‘ARR’ which will look like [0,1] after performing the first operation and then assigning the values in ‘ARR’ to ‘permArray’. So ‘permArray’ will become [0, 1] which is the same as the original array. So the output will be 1.
For the second test case,
Initially the ‘permArray’ will look like [0,1,2,3]. Then we will create a new array ‘ARR’ which will look like [0,2,1,3] after performing the first operation and then assigning the values in ‘ARR’ to ‘permArray’. So ‘permArray’ will become [0,2,1,3]. Then again we will create a new array ‘ARR’ which will look like [0,1, 2, 3] after performing the second operation and then assigning the values in ‘ARR’ to ‘permArray’. So ‘permArray’ will become [0,1,2,3] which is the same as the original array. So the output will be 2.
2
6
8
4
3
Try to simulate the process exactly as mentioned in the problem statement.
Approach:
Algorithm:
O(N^2), where ‘N’ is the length of the permutation.
Constructing the array permArray will take O(N) time. Each element in the permArray forms a cycle and comes back to its original state in atmost N steps which will take O(N) time, and in each iteration, we iterate through all the N elements of the permArray. Therefore, the overall time complexity will be O(N^2).
O(N), where ‘N’ is the length of the permutation.
Since we are constructing two arrays permArray, and the ARR which takes O(N) space. So overall space complexity will be O(N).