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] = startp[i]andp[i+1]differ by only one bit in their binary representationp[0]andp[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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code