Minimum Number of Operations to Reinitialize a Permutation — LeetCode 1806 Python Solution
- Problem
- #1806
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an even integer n. You initially have a permutation perm of size n where perm[i] == i (0-indexed).
Example
- Input
- n = 2
- Output
- 1
- Explanation
- perm = [0,1] initially.
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation?
- LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation cover?
- LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation is tagged Array, Math and Simulation on LeetCode.