#1238
Circular Permutation in Binary Representation
MediumMathBacktrackingBit ManipulationBit ManipulationBacktrackingGray Code
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses Gray code to generate a sequence where each number differs from the previous one by exactly one bit. This method is efficient and directly constructs the required permutation without generating all possibilities.
⚙️
Algorithm
3 steps- 1Step 1: Generate the Gray code sequence for n bits using the formula: gray(i) = i ^ (i >> 1).
- 2Step 2: Rotate the sequence such that it starts with the given 'start' value.
- 3Step 3: Return the rotated sequence.
solution.py6 lines
1# Full working Python code
2
3def circular_permutation_optimal(n, start):
4 gray_code = [(i ^ (i >> 1)) for i in range(2 ** n)]
5 start_index = gray_code.index(start)
6 return gray_code[start_index:] + gray_code[:start_index]ℹ
Complexity note: Generating the Gray code sequence takes O(n) time, and rotating the array also takes O(n), leading to an overall complexity of O(n).
- 1Gray code ensures that only one bit changes between consecutive numbers, which is crucial for the problem.
- 2The optimal solution leverages mathematical properties to avoid unnecessary permutations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.