Problem 1806

Abstract / Summary

Find the smallest number of times you must apply a specific transformation to a permutation before it returns to its original form.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
22 lines | 577 bytes | submitted March 21, 2024 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (30k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 i is odd, the source index is n // 2 + (i - 1) // 2.
  • If i is even, the source index is i // 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.56 | σ = 1.40

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
22 links | 13 authors | 7 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   March 21, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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