#1806
Minimum Number of Operations to Reinitialize a Permutation
MediumArrayMathSimulationArraySimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution recognizes that the operations form a cycle. By tracking the position of each index, we can determine how many operations it takes to return to the original state without simulating each operation.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to track the number of operations.
- 2Step 2: Use a loop to track the position of each index until it returns to the original index.
- 3Step 3: Count the number of operations needed for each index and return the maximum.
solution.py19 lines
1# Full working Python code
2
3def min_operations(n):
4 operations = 0
5 for start in range(n):
6 current = start
7 count = 0
8 while True:
9 count += 1
10 if current % 2 == 0:
11 current //= 2
12 else:
13 current = n // 2 + (current - 1) // 2
14 if current == start:
15 break
16 operations = max(operations, count)
17 return operations
18
19print(min_operations(4)) # Example usageℹ
Complexity note: The time complexity is O(n) because we iterate through each index once and track its position, leading to a linear time complexity overall.
- 1The operations form a cycle, and tracking the position of each index helps determine the number of operations needed.
- 2The maximum number of operations across all indices gives the total operations required to return to the original permutation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.