Circular Permutation in Binary Representation - Problem

Imagine you have a circular sequence of numbers where each adjacent pair differs by exactly one bit in their binary representation - this is called a Gray Code sequence. Your task is to construct such a sequence starting from a specific number!

Given two integers n and start, return any permutation of all numbers from 0 to 2n - 1 such that:

  • The first element equals start
  • Each consecutive pair of numbers differs by exactly one bit in binary
  • The sequence is circular - the last element also differs from the first by exactly one bit

Example: For n = 3, start = 2, one valid sequence is [2, 6, 7, 5, 4, 0, 1, 3]
Binary: [010, 110, 111, 101, 100, 000, 001, 011] - notice each pair differs by one bit!

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 2, start = 3
โ€บ Output: [3, 2, 0, 1]
๐Ÿ’ก Note: Binary sequence: [11, 10, 00, 01]. Each adjacent pair differs by 1 bit, and 01 ^ 11 has only 1 bit difference (circular property).
example_2.py โ€” Larger Input
$ Input: n = 3, start = 2
โ€บ Output: [2, 6, 7, 5, 4, 0, 1, 3]
๐Ÿ’ก Note: Binary: [010, 110, 111, 101, 100, 000, 001, 011]. Starts with 2, each step flips exactly one bit, and 011 ^ 010 = 1 bit difference.
example_3.py โ€” Edge Case
$ Input: n = 1, start = 0
โ€บ Output: [0, 1]
๐Ÿ’ก Note: Smallest case: binary [0, 1]. Only one bit to flip, satisfies all conditions trivially.

Visualization

Tap to expand
๐Ÿ” Binary Lock Sequence (n=3, start=2)010Start: 2110Flip bit 2111Flip bit 0101Flip bit 1100Flip bit 0000Flip bit 2001Flip bit 0011Back to start!๐Ÿ”ต Start Position ๐ŸŸข Valid Next States ๐ŸŸก Complete CycleRed dashed line shows circular property: last connects back to first
Understanding the Visualization
1
Initialize
Start at the given combination and mark it as the first position
2
Generate Pattern
Use Gray code's reflection property to systematically visit all combinations
3
Transform
Apply XOR transformation to rotate the entire sequence to start from desired position
4
Verify
Ensure the last combination differs from first by exactly one switch flip
Key Takeaway
๐ŸŽฏ Key Insight: Gray codes have a beautiful recursive structure that guarantees the circular property, making XOR transformation the elegant optimal solution!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(2^n)

We generate exactly 2^n elements once and apply constant time transformations

n
2n
โš  Quadratic Growth
Space Complexity
O(2^n)

Storage for the result array containing all 2^n permutation elements

n
2n
โš  Quadratic Space

Constraints

  • 1 โ‰ค n โ‰ค 17
  • 0 โ‰ค start < 2n
  • Note: The answer sequence length is exactly 2n
Asked in
Google 42 Facebook 28 Microsoft 35 Amazon 22
31.4K Views
Medium Frequency
~25 min Avg. Time
892 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