Minimum Number of Operations to Reinitialize a Permutation Problem
Description
LeetCode Problem 1806.
You are given an even integer n. You initially have a permutation perm of size n where perm[i] == i (0-indexed).
In one operation, you will create a new array arr, and for each i:
- If
i % 2 == 0, thenarr[i] = perm[i / 2]. - If
i % 2 == 1, thenarr[i] = perm[n / 2 + (i - 1) / 2].
You will then assign arr to perm.
Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.
Example 1:
Input: n = 2
Output: 1
Explanation: perm = [0,1] initially.
After the 1^st operation, perm = [0,1]
So it takes only 1 operation.
Example 2:
Input: n = 4
Output: 2
Explanation: perm = [0,1,2,3] initially.
After the 1^st operation, perm = [0,2,1,3]
After the 2^nd operation, perm = [0,1,2,3]
So it takes only 2 operations.
Example 3:
Input: n = 6
Output: 4
Constraints:
2 <= n <= 1000nis even.
Solution
Approach: Track One Element
Look at where one operation sends each position. The elements of the first half of the old array land on the even positions of the new array, in order, and the elements of the second half land on the odd positions. So an element at index i moves to 2i if i < n/2, and to 2(i - n/2) + 1 otherwise.
Every round applies the same movement, so the array is back to the identity exactly when every element is back at its own index. The movement is a permutation, so the elements trace cycles, and following the element that starts at index 1 is enough: its cycle is the one that determines the answer, so we count rounds until it returns to index 1.
Complexity: O(n) time and O(1) extra space.
class Solution:
def reinitializePermutation(self, n: int) -> int:
ans, i = 0, 1
while 1:
ans += 1
if i < n >> 1:
i <<= 1
else:
i = (i - (n >> 1)) << 1 | 1
if i == 1:
return ans