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 Sequence Generator INPUT n = 2 (number of bits) 2-bit Binary Numbers 00 = 0 01 = 1 10 = 2 11 = 3 Sequence size: 2^2 = 4 Adjacent numbers must differ by 1 bit ALGORITHM STEPS 1 Start with 0 Base case: [0] 2 Mirror & Prefix Reverse list, add 2^(i-1) 3 Iteration 1 (i=1) [0] --> [0, 1] 4 Iteration 2 (i=2) [0,1] --> [0,1,3,2] Formula: i XOR (i >> 1) 0 XOR 0 = 0 (00) 1 XOR 0 = 1 (01) 2 XOR 1 = 3 (11) 3 XOR 1 = 2 (10) FINAL RESULT Gray Code Sequence [0, 1, 3, 2] Binary Verification 0 00 1 01 3 11 2 10 [OK] 00 --> 01: 1 bit diff [OK] 01 --> 11: 1 bit diff [OK] 11 --> 10: 1 bit diff [OK] 10 --> 00: 1 bit diff Valid Gray Code! Key Insight: Gray code can be generated using the formula: G(i) = i XOR (i >> 1). This works because XOR with right-shifted value ensures only one bit changes between consecutive numbers. The sequence forms a cycle where first and last elements also differ by exactly one bit. Time: O(2^n), Space: O(2^n) TutorialsPoint - Gray Code | Optimal Solution (XOR Method)
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