Gray Code

The problem involves generating Gray codes for a given number of bits. Gray code is an ordering of the binary numeral system such that two successive values differ in only one bit.

The easiest way to solve this problem is to use the mathematical relationship between binary numbers and Gray codes. For a binary number B, the corresponding Gray code G is given by:

G = B XOR (B » 1)

Here XOR is the bitwise exclusive or operation, and » is a right shift. This formula gives us an easy way to generate all the Gray codes for n bits: we simply count from 0 to 2^n - 1 in binary, and convert each number to its corresponding Gray code.

Python solution:

1
2
3
4
5
6
7
8
class Solution:
    def grayCode(self, n: int) -> List[int]:
        result = []
        for i in range(1 << n):
            # calculate the gray code
            gray = i ^ (i >> 1)
            result.append(gray)
        return result

This solution first calculates the number of possible Gray codes using the formula 2^n (1 « n in binary). Then it generates each binary number from 0 to 2^n - 1, converts it to the corresponding Gray code using the formula B XOR (B » 1), and adds it to the result. The result is then returned.

This solution works in O(2^n) time and uses O(2^n) space to store the result, where n is the number of bits.