Python 1806.py
class Solution:
def reinitializePermutation(self, n: int) -> int:
# https://oeis.org/A002326
# just brute force
need = list(range(n))
have = need.copy()
step = 0
while have != need or step == 0:
next = []
for i, h in enumerate(have):
if i & 1:
index = n // 2 + (i - 1) // 2
else:
index = i // 2
next.append(have[index])
have = next
step += 1
return step
Difficulty
and has an acceptance rate of about 73% (30k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The reinitializePermutation method computes how many applications of a specific permutation transformation are required to bring an array of length n back to its original ordering. It starts with an identity permutation, repeatedly applies the transformation defined by the problem, and counts the iterations until the permutation matches the initial state again.
Key Steps
The function begins by constructing the target ordering, which is simply the list of integers from 0 to n-1. This list is stored in the variable need and duplicated into have, which will be mutated during the simulation.
need = list(range(n))
have = need.copy()
A counter named step is initialized to zero. The main loop continues while the current permutation have differs from the original need, or when no iteration has yet occurred (ensuring at least one transformation is performed).
step = 0
while have != need or step == 0:
Inside the loop a new list next is built. For each index i in the current permutation, the code determines the source index according to the rule:
- If
iis odd, the source index isn // 2 + (i - 1) // 2. - If
iis even, the source index isi // 2.
The element at that source index in have is appended to next.
next = []
for i, h in enumerate(have):
if i & 1:
index = n // 2 + (i - 1) // 2
else:
index = i // 2
next.append(have[index])
After constructing the transformed permutation, have is replaced with next, and the step counter is incremented.
have = next
step += 1
When the loop condition fails-meaning the permutation has returned to its original ordering-the method returns the total number of steps taken.
return step
Edge Cases Handled
The implementation gracefully handles the smallest possible input size. When n equals 1, the initial permutation [0] is already identical to the target, but the step == 0 clause forces a single iteration, after which the loop exits and the function returns 1. This matches the expected behavior for a trivial permutation.
Because the index calculation uses integer division (//) and works uniformly for both even and odd indices, the code correctly processes any integer n. The arithmetic for odd indices adds n // 2 to the half-offset, ensuring that the source index stays within bounds for all valid i. The loop condition guarantees termination even when the transformation yields the original ordering after just one step.
Performance Optimizations Observed
The algorithm relies on a single auxiliary list next that is recreated each iteration, avoiding the overhead of more complex data structures. By using bitwise & 1 to test parity, the code performs a fast check for odd indices without invoking higher-level functions. The calculation of the source index is performed with simple arithmetic operations-integer division and subtraction-both of which are inexpensive in Python.
Copying the initial permutation with need.copy() provides a shallow duplicate that can be compared directly to have without additional processing. The direct list comparison in the loop condition leverages Python’s optimized sequence equality check, which short-circuits as soon as a mismatch is found, reducing unnecessary work when the permutations diverge early in the sequence.
Overall, the implementation balances clarity with efficient use of built-in operations, resulting in a straightforward simulation that runs with minimal overhead for each iteration.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered cards laid out on the floor, and you want to shuffle them around using a special set of rules. This code is like a little robot designed to organize those cards over and over again.
First, the robot makes a copy of the cards in their perfect starting order so it remembers how they should look when everything is finished. Then, it starts a game of moving every single card to a new spot based on a pattern. If the card is in an even position, it moves to the front half of the line, and if it is in an odd position, it hops over to the back half.
After all the cards have moved to their new homes, the robot looks at the line to see if the cards have returned to their original order. If the cards are still scrambled, the robot performs the entire shuffle process again and counts how many times it takes to get them back to that perfect starting line. It keeps repeating this loop until the cards are exactly where they began.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | ||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| haoel | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| haoel | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 3079: Find the Sum of Encrypted Integers
- problem 1111: Maximum Nesting Depth of Two Valid Parentheses Strings
- problem 1727: Largest Submatrix With Rearrangements
- problem 2186: Minimum Number of Steps to Make Two Strings Anagram II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality