VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-n-bit-gray-codes/

⇱ Generate n-bit Gray Codes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate n-bit Gray Codes

Last Updated : 3 Apr, 2026

Given a number n, generate bit patterns from 0 to 2^(n-1) such that successive patterns differ by one bit.

Examples:

Input: n = 2
Output: 00 01 11 10
Explanation: We begin with all 0s, and then add the smallest next number that has only one bit difference, we keep adding this way to generate the full sequence.

Input: n = 3
Output: 000 001 011 010 110 111 101 100

Using Reflection Method

The idea is based on the fact that n bit Gray codes can be generated using (n-1) bit Gray codes. We start with the 1 bit Gray code, which is {0, 1}.

How to generate n bit Gray code from (n-1) Gray codes?

  1. Take (nāˆ’1) bit Gray code
  2. Copy it in reverse
  3. Prefix 0 to original list and prefix 1 to reversed list
  4. Concatenate the two lists generated in the previous step and we have the n bit Gray code.

Why does this work?

  • Since we create two lists of same size as n-1 bit Gray codes, the count of n bit Gray codes is double of the (n-1) bit Gray codes.
  • Prefix 0 and 1 ensures that the first half starts with 0 and second half starts with 1. So no overlap between halves
  • Since we reverse the second half before prefixing with 1, the end of first list and first of second list were same before appending. After concatenating two lists, these two elements only differ by first bit.

Output
000 001 011 010 110 111 101 100 

Time Complexity: O(n*(2^n))

Auxiliary Space: O(1), while the overall space complexity is O(n*(2^n)) to store the resulting Gray code sequence.

Using Bit Manipulation

We directly generate the i'th Gray Code using the formula Gray(i) = i XOR (i >> 1), we iterate from 0 to 2^(n - 1), apply this formula for each value, convert the result into an n-bit binary string, store it, and finally print the sequence.

Why does this formula work?

If we take a closer look at the formula,

  • When we do (i >> 1), all bits shift one position to the right, least significant bit is dropped and a 0 is inserted at the left.
  • When we do XOR of i with (i >> 1), all trailing flips cancel out in XOR
  • Only the first changing position survives

Output
0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000 

Time Complexity: O(n*(2^n))

Auxiliary Space: O(n), while the overall space complexity is O(n*(2^n)) to store the resulting Gray code sequence.

Comment