Magicsheet logo

Circular Permutation in Binary Representation

Medium
75%
Updated 8/1/2025

Circular Permutation in Binary Representation

What is this problem about?

Given two integers nn and start, you need to return a permutation of numbers from 0 to 2n12^n - 1 such that:

  1. The first element is start.
  2. Every two adjacent elements (including the first and last) differ by exactly one bit in their binary representation. This is essentially asking for a Gray Code sequence that starts at a specific number.

Why is this asked in interviews?

Walmart Labs and other companies use this to test your knowledge of Bit Manipulation and Gray Codes. It evaluations your ability to identify that a circular bit-alternating sequence is a property of the Gray Code system and whether you can transform a standard sequence to start at a given value while maintaining its properties.

Algorithmic pattern used

The pattern is Gray Code generation combined with Bitwise XOR. The standard nn-bit Gray Code sequence for ii is i ^ (i >> 1). To make the sequence start at start while keeping the "one-bit difference" property, you can XOR every element in the standard Gray Code sequence with start. Since A ^ B and (A+1) ^ B still differ by only one bit if A and A+1 differed by one bit in Gray space, the property is preserved.

Example explanation

n=2n = 2, start = 3 (11 in binary)

  1. Standard 2-bit Gray Code: [0, 1, 3, 2] (00, 01, 11, 10)
  2. XOR each with 3 (11):
    • 03=30 \oplus 3 = 3 (11)
    • 13=21 \oplus 3 = 2 (10)
    • 33=03 \oplus 3 = 0 (00)
    • 23=12 \oplus 3 = 1 (01) Result: [3, 2, 0, 1]. Each adjacent pair differs by one bit.

Common mistakes candidates make

A common error is trying to use backtracking to find the permutation. While it works for very small nn, it is O(2n!)O(2^n!) and will fail for n>4n > 4. Another mistake is trying to "rotate" the Gray Code sequence instead of using the XOR property, which is more complex to implement.

Interview preparation tip

Gray Code is a specific binary numeral system where two successive values differ in only one bit. The formula G(i) = i ^ (i / 2) is one of the most useful bitwise tricks to have in your pocket.

Similar Questions