Circular Permutation in Binary Representation - Problem

Given two integers n and start, your task is to 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

This creates a circular Gray code sequence starting from the given number.

Input & Output

Example 1 — Small Case
$ Input: n = 2, start = 3
Output: [3,2,0,1]
💡 Note: For n=2, we need permutation of [0,1,2,3]. Starting with 3 (binary 11), we can go to 2 (10), then 0 (00), then 1 (01), and back to 3 (11). Each adjacent pair differs by exactly one bit.
Example 2 — Start from Zero
$ Input: n = 3, start = 0
Output: [0,1,3,2,6,7,5,4]
💡 Note: Standard Gray code sequence for n=3 starting from 0. Binary sequence: 000→001→011→010→110→111→101→100, each differing by one bit.
Example 3 — Minimum Case
$ Input: n = 1, start = 1
Output: [1,0]
💡 Note: For n=1, only two numbers [0,1]. Starting with 1 (binary 1), go to 0 (binary 0). They differ by one bit and 0→1 also differs by one bit, completing the circle.

Constraints

  • 1 ≤ n ≤ 16
  • 0 ≤ start < 2n

Visualization

Tap to expand
Circular Gray Code: One Bit Difference Between Adjacent NumbersInput: n=2, start=3Need permutation of [0,1,2,3]Starting with 3311210000101Valid Sequence:[3, 2, 0, 1]3→2: 11→10 (1 bit diff)2→0: 10→00 (1 bit diff)0→1: 00→01 (1 bit diff)1→3: 01→11 (1 bit diff) ✓Key: Each arrow represents a single bit flip
Understanding the Visualization
1
Input
Given n=2, start=3, need permutation of [0,1,2,3]
2
Process
Each adjacent pair must differ by exactly one bit
3
Output
Valid circular sequence starting and ending near start
Key Takeaway
🎯 Key Insight: Gray code ensures each step changes exactly one bit, and XOR with start rotates the sequence to begin from any position
Asked in
Google 15 Facebook 12 Microsoft 8 Amazon 6
18.5K Views
Medium Frequency
~25 min Avg. Time
324 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen