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).