Circular Permutation in Binary Representation

medium bit manipulation gray code xor

Problem

Given integers n and start, return any permutation p of the integers in the range [0, 2n − 1] such that p[0] = start, every pair of adjacent elements differs by exactly one bit, and the first and last elements also differ by exactly one bit (the sequence is circular).

Inputn = 2, start = 3
Output[3, 2, 0, 1]
3→2 flips one bit (11→10), 2→0 (10→00), 0→1 (00→01), and 1→3 (01→11) closes the cycle. It is the standard Gray code [0,1,3,2] XORed with start = 3.

def circular_permutation(n, start):
    result = []
    for i in range(1 << n):
        gray = i ^ (i >> 1)
        result.append(start ^ gray)
    return result
function circularPermutation(n, start) {
  const result = [];
  for (let i = 0; i < (1 << n); i++) {
    const gray = i ^ (i >> 1);
    result.push(start ^ gray);
  }
  return result;
}
class Solution {
    public List<Integer> circularPermutation(int n, int start) {
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < (1 << n); i++) {
            int gray = i ^ (i >> 1);
            result.add(start ^ gray);
        }
        return result;
    }
}
vector<int> circularPermutation(int n, int start) {
    vector<int> result;
    for (int i = 0; i < (1 << n); i++) {
        int gray = i ^ (i >> 1);
        result.push_back(start ^ gray);
    }
    return result;
}
Time: O(2n) Space: O(2n)