Circular Permutation in Binary Representation — LeetCode 1238 Python Solution

MediumBit ManipulationMathBacktracking
Problem
#1238
Reading time
2 min

The problem

Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p[0] = start p[i] and p[i+1] differ by only one bit in their binary representation.

Example

Input
n = 2, start = 3
Output
[3,2,0,1]
Explanation
The binary representation of the permutation is (11,10,00,01).

Python solution

Python
class Solution:
    def circularPermutation(self, n: int, start: int) -> List[int]:
        g = [i ^ (i >> 1) for i in range(1 << n)]
        j = g.index(start)
        return g[j:] + g[:j]

Complexity

MeasureComplexity
TimeO(2^n)
SpaceO(2^n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1238. Circular Permutation in Binary Representation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1238. Circular Permutation in Binary Representation?
LeetCode 1238. Circular Permutation in Binary Representation is rated Medium on LeetCode.
What is the time complexity of LeetCode 1238. Circular Permutation in Binary Representation?
The Python solution on this page runs in O(2^n).
What is the space complexity of LeetCode 1238. Circular Permutation in Binary Representation?
The Python solution on this page uses O(2^n) auxiliary space.
What topics does LeetCode 1238. Circular Permutation in Binary Representation cover?
LeetCode 1238. Circular Permutation in Binary Representation is tagged Bit Manipulation, Math and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview