Circular Permutation in Binary Representation

Given two integers n and start, 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.
  • p[0] and p[2^n - 1] must also differ by only one bit in their binary representation.
Example 1
Inputn = 2, start = 3
Output[3,2,0,1]
The binary representation of the permutation is (11, 10, 00, 01), and all adjacent elements differ by one bit; another valid permutation is [3, 1, 0, 2].
Example 2
Inputn = 3, start = 2
Output[2,6,7,5,4,0,1,3]
The binary representation of the permutation is (010, 110, 111, 101, 100, 000, 001, 011).

Constraints

  • 1 <= n <= 16
  • 0 <= start < 2 ^ n

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate