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
Gray Code: n=2 → Generate 2-bit sequenceInput: n = 22Gray Code PropertyAdjacent numbers differ by exactly 1 bitOutput Sequence013200011110Verification: 0→1 (bit 0), 1→3 (bit 1), 3→2 (bit 0), 2→0 (bit 1) ✓Result: [0, 1, 3, 2]
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
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~15 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