Gray Code - Problem
A Gray Code (also known as reflected binary code) is a fascinating sequence where adjacent numbers differ by exactly one bit! Think of it as a clever way to count where you change only one digit at a time.
Given an integer n, you need to generate a valid n-bit Gray Code sequence that satisfies these conditions:
- Contains exactly
2nintegers in the range[0, 2n - 1] - Starts with
0 - Each integer appears exactly once
- Adjacent integers differ by exactly one bit
- The first and last integers also differ by exactly one bit (circular property)
Example: For n = 2, a valid sequence is [0, 1, 3, 2]
Binary: [00, 01, 11, 10] - notice each pair differs by one bit!
Input & Output
example_1.py โ Basic case
$
Input:
n = 2
โบ
Output:
[0, 1, 3, 2]
๐ก Note:
For n=2, we need 4 numbers (2ยฒ). The sequence [0,1,3,2] in binary is [00,01,11,10]. Each adjacent pair differs by exactly 1 bit: 00โ01 (bit 0), 01โ11 (bit 1), 11โ10 (bit 0), and 10โ00 (bit 1, circular).
example_2.py โ Single bit
$
Input:
n = 1
โบ
Output:
[0, 1]
๐ก Note:
For n=1, we need 2 numbers (2ยน). The sequence [0,1] in binary is [0,1]. They differ by exactly 1 bit, and 1โ0 also differs by 1 bit (circular property).
example_3.py โ Edge case
$
Input:
n = 3
โบ
Output:
[0, 1, 3, 2, 6, 7, 5, 4]
๐ก Note:
For n=3, we need 8 numbers (2ยณ). This sequence follows the mirror construction: G(3) is built from G(2)=[0,1,3,2] by appending its reverse [2,3,1,0] with MSB set, giving [6,7,5,4].
Visualization
Tap to expand
Understanding the Visualization
1
Start at 00
Begin with all switches OFF
2
Flip rightmost
Change to 01 - only rightmost switch changes
3
Flip left switch
Change to 11 - only left switch changes
4
Flip rightmost
Change to 10 - only rightmost switch changes
5
Return to start
Back to 00 - only left switch changes
Key Takeaway
๐ฏ Key Insight: Gray Code follows a beautiful pattern where we can generate the sequence using either the mathematical formula i โ (i >> 1) or the recursive mirror construction, both achieving optimal O(2^n) time complexity!
Time & Space Complexity
Time Complexity
O((2^n)!)
We try all permutations of 2^n numbers, leading to factorial time complexity
โ Quadratic Growth
Space Complexity
O(2^n)
Recursion stack depth can go up to 2^n levels, plus storing the sequence
โ Quadratic Space
Constraints
- 1 โค n โค 16
- Important: The result must contain exactly 2n unique integers
- All integers must be in range [0, 2n - 1]
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code