Python 1238.py
class Solution:
def circularPermutation(self, n: int, start: int) -> List[int]:
# generic Gray-Code (as strings)
have = [ "" ]
for bits in range(n):
more = []
for h in have:
more.append("0" + h)
for h in have[::-1]:
more.append("1" + h)
have = more
# convert to ints
binary = [ int(h, 2) for h in have ]
# rotate such that it starts with "start"
pos = binary.index(start)
return binary[pos : ] + binary[ : pos]
Difficulty
and has an acceptance rate of about 73% (30k+ submissions).
Typical patterns to solve this problem:
- Backtracking
- Bit Manipulation
- Math
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 provided implementation computes a circular permutation of the Gray code sequence for a given bit length n and rotates it so that the permutation begins with the integer start. The algorithm proceeds in three conceptual phases: constructing the Gray code as binary strings, converting those strings to integer values, and performing a rotation to align the sequence with the required starting element.
Gray-code construction
The first phase builds the classic binary reflected Gray code using a list of string representations. It begins with a single empty string and iteratively expands the list for each bit position. For each iteration a temporary list more is populated by prefixing a '0' to every existing entry, then by prefixing a '1' to the entries in reverse order. This mirroring technique guarantees that consecutive entries differ by exactly one bit, which is the defining property of Gray codes.
have = [ "" ]
for bits in range(n):
more = []
for h in have:
more.append("0" + h)
for h in have[::-1]:
more.append("1" + h)
have = more
The use of a temporary list avoids repeated insertions at the front of the original list, which would be costly. By constructing the new list in a forward direction and then assigning it back to have, the code benefits from Python’s efficient list allocation for the known final size of 2**n.
Conversion to integer values
After the string list is complete, a list comprehension transforms each binary string into its numeric counterpart using base-2 conversion. This step yields the canonical Gray-code sequence as a list of integers.
binary = [ int(h, 2) for h in have ]
The comprehension runs in a single pass, leveraging the built-in int conversion which is implemented in C and therefore fast. No intermediate structures are created beyond the resulting list.
Rotation to the required start
The final phase locates the position of the desired start value within the integer list and slices the list to rotate it. The index operation scans the list once to find the matching element, and the subsequent slice concatenation produces a new list that begins with start while preserving the circular order.
pos = binary.index(start)
return binary[pos:] + binary[:pos]
Slicing in Python creates shallow copies of the relevant sub-ranges, and the concatenation builds the final result in a single allocation of the required size. This approach avoids element-wise insertion or manual shifting, which would be less efficient.
Edge-case handling
When n is zero the outer loop does not execute, leaving have as a list containing the empty string. Converting this empty string with base-2 yields the integer 0, so the function correctly returns [0] for any start equal to 0. The index lookup therefore succeeds without special-case code.
If start equals the first element of the generated Gray code, the index is 0 and the slice operation returns the original list unchanged. Conversely, if start is the last element, the slice produces a list where the last element moves to the front, demonstrating that the rotation works for any valid position.
The algorithm also implicitly assumes that start lies within the range [0, 2**n - 1]. Because the Gray code generation covers exactly that range, the index call will always locate start when the precondition holds, and the function will raise a clear exception otherwise, which is appropriate for misuse.
Performance considerations
The construction of the Gray code uses a deterministic pattern that doubles the list size on each iteration. By pre-allocating a fresh list more each time, the code sidesteps the overhead of repeated list resizing. The reverse iteration (have[::-1]) is performed on a view of the existing list, which is a fast operation in CPython because it creates a new list of references rather than copying the underlying objects.
The conversion step benefits from the highly optimized C implementation of int(..., 2). Because the comprehension processes each string exactly once, the overall work is linear in the number of generated codes.
The rotation leverages Python’s slice semantics, which are implemented in C and produce new list objects with a single memory allocation for the combined result. This avoids the need for explicit loops to reposition elements, yielding a concise and performant final step.
Overall, the code follows a clear, step-wise structure that aligns with the mathematical definition of reflected Gray codes while employing Python’s built-in operations to keep the runtime overhead minimal.
ELI5 - Simplified Explanation
Imagine a long train made of special blocks, where each block has a secret code written on it in ones and zeros. To build this train, the code starts with just one empty block. Then, it carefully builds new blocks by taking the ones it already has, adding a zero to the front of them, and then adding a one to the front of the same blocks but in backwards order. This special trick makes sure that every block is just a little bit different from the one sitting right next to it, which is like a fun puzzle rule.
Once all the blocks are lined up in a long row, the second part of the code changes those zeros and ones back into regular numbers that people can read. Think of turning those secret codes into numbers like one, two, or three.
Finally, the code looks for the number you picked to be at the front of the line. It grabs that spot where your number lives and carefully picks up the whole line of blocks, moving the pieces that came before your number to the very back of the line. Now, the train starts exactly where you wanted it to begin, and it still keeps that same special rule where neighbors are almost exactly the same. The whole line becomes a circle where the end connects back to the start, and every piece fits together perfectly.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
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++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| MemoryLimitExceeded | C++ | Python | ||||||
| Progiez | C++ | Python | Java | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| MemoryLimitExceeded | Python, C++ | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# |
Videos
Solved On The Same Day
- problem 851: Loud and Rich
- problem 1807: Evaluate the Bracket Pairs of a String
- problem 1992: Find All Groups of Farmland
- problem 2177: Find Three Consecutive Integers That Sum to a Given Number
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