Gray Code - Problem
An n-bit gray code sequence is a sequence of 2^n integers where:
- Every integer is in the inclusive range
[0, 2^n - 1] - The first integer is
0 - An integer appears no more than once in the sequence
- The binary representation of every pair of adjacent integers differs by exactly one bit
- The binary representation of the first and last integers differs by exactly one bit
Given an integer n, return any valid n-bit gray code sequence.
Input & Output
Example 1 — Basic Case (n=2)
$
Input:
n = 2
›
Output:
[0,1,3,2]
💡 Note:
Binary: [00,01,11,10]. Each adjacent pair differs by one bit: 00→01 (bit 0), 01→11 (bit 1), 11→10 (bit 0), 10→00 (bit 1, wraps around).
Example 2 — Minimum Case (n=1)
$
Input:
n = 1
›
Output:
[0,1]
💡 Note:
Binary: [0,1]. Only two 1-bit numbers: 0→1 differs by bit 0, and 1→0 wraps around differing by bit 0.
Example 3 — Edge Case (n=0)
$
Input:
n = 0
›
Output:
[0]
💡 Note:
Only one 0-bit number exists: 0. Single element trivially satisfies Gray code properties.
Constraints
- 0 ≤ n ≤ 16
- Answer is guaranteed to fit in a 32-bit integer
Visualization
Tap to expand
Understanding the Visualization
1
Input
n = 2 (want 2-bit Gray code)
2
Process
Build sequence where adjacent numbers differ by one bit
3
Output
[0,1,3,2] with binary [00,01,11,10]
Key Takeaway
🎯 Key Insight: Gray codes follow a recursive doubling pattern with bit manipulation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code