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 Permutation in Binary Representation INPUT n = 2 start = 3 All numbers: 0 to 2^2-1 0 = 00 (binary) 1 = 01 (binary) 2 = 10 (binary) 3 = 11 (binary) Start: 3 Constraint: Adjacent numbers must differ by 1 bit only Must form a cycle: p[0] and p[last] differ by 1 bit ALGORITHM STEPS 1 Generate Gray Code G(i) = i XOR (i >> 1) 0 1 3 2 2 Find start position Locate start=3 in Gray Position: index 2 3 XOR with start Each G(i) XOR start Shifts sequence to start 0 XOR 3 = 3 1 XOR 3 = 2 3 XOR 3 = 0 2 XOR 3 = 1 4 Verify circular Check: p[0]=3 (11) p[3]=1 (01) differ 1 bit OK FINAL RESULT Output Permutation: 3 11 2 10 0 00 1 01 Circular Gray Code: 3 2 0 1 1 bit 1 bit 1 bit 1 bit Valid Circular Gray! Key Insight: Gray code naturally provides a sequence where adjacent numbers differ by exactly 1 bit. By XORing each Gray code value with the start value, we shift the entire sequence to begin at start while preserving the 1-bit difference property. Formula: result[i] = (i XOR (i >> 1)) XOR start TutorialsPoint - Circular Permutation in Binary Representation | Optimal Solution (Gray Code + XOR)
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