Circular Permutation in Binary Representation Problem
Description
LeetCode Problem 1238.
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :
p[0] = startp[i]andp[i+1]differ by only one bit in their binary representation.p[0]andp[2^n -1]must also differ by only one bit in their binary representation.
Example 1:
Input: n = 2, start = 3
Output: [3,2,0,1]
Explanation: The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]
Example 2:
Input: n = 3, start = 2
Output: [2,6,7,5,4,0,1,3]
Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).
Constraints:
1 <= n <= 160 <= start < 2 ^ n
Solution
Approach: Gray Code Shifted by start
A sequence of all numbers 0 .. 2^n - 1 where neighbours, including the last and the first, differ in one bit is a cyclic Gray code. The standard one is gray(i) = i ^ (i >> 1): going from i to i + 1 changes exactly one bit of gray(i), and gray(2^n - 1) = 2^(n-1) differs from gray(0) = 0 in one bit, so the cycle closes.
The sequence must start at start, not at 0. Instead of finding start in the Gray code and rotating, XOR every element with start:
gray(0) ^ start = start, so the first element is right.(a ^ start) ^ (b ^ start) = a ^ b, so two neighbours still differ in exactly the bits whereaandbdiffer: one bit.- XOR with a fixed value is a bijection on
0 .. 2^n - 1, so we still get a permutation.
So p[i] = i ^ (i >> 1) ^ start for i = 0 .. 2^n - 1. Any valid permutation is accepted, so this answer may differ from the examples.
Complexity: O(2n) time and O(1) extra space besides the answer.
class Solution:
def circularPermutation(self, n: int, start: int) -> List[int]:
# i ^ (i >> 1) is the Gray code: neighbours (and the last and first) differ in one bit.
# XOR-ing every code with start keeps that, and puts start first.
return [i ^ (i >> 1) ^ start for i in range(1 << n)]