An n-bit gray code sequence is a sequence of 2n integers where:
[0, 2n - 1],0,Given an integer n, return any valid n-bit gray code sequence.
Example 1:
Input: n = 2 Output: [0,1,3,2] Explanation: The binary representation of [0,1,3,2] is [00,01,11,10]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit
Example 2:
Input: n = 1 Output: [0,1]
Constraints:
1 <= n <= 16Problem Overview: Gray code is a sequence of 2^n integers where each consecutive value differs by exactly one bit. Given n, generate any valid sequence of n-bit Gray codes starting from 0.
Approach 1: Bit Manipulation Formula (O(2^n) time, O(1) extra space)
The most direct solution uses a known property of Gray codes: the i-th Gray code equals i ^ (i >> 1). Iterate from 0 to 2^n - 1, compute the value using a bitwise XOR between the number and itself shifted right by one bit, and append the result. The XOR operation ensures only one bit changes between consecutive values. This approach relies on bit manipulation and simple iteration, producing the sequence in linear time relative to the output size. Since we only compute values on the fly, the algorithm uses constant auxiliary space besides the output list.
Approach 2: Recursive Gray Code Generation (O(2^n) time, O(2^n) space)
Gray codes follow a reflective pattern. For n bits, first generate the sequence for n-1 bits. Keep that list as the first half. Then reverse the list and prefix each value with a leading 1 (equivalent to adding 1 << (n-1)). Appending this modified reversed sequence creates a valid Gray code order where adjacent numbers differ by one bit. This recursive construction highlights the mathematical structure of Gray codes and naturally fits backtracking or recursive thinking. The main cost comes from storing and expanding the list at each level.
Example pattern for n = 3: start with [0]. For n = 1 → [0,1]. For n = 2 → [0,1,3,2]. For n = 3, reflect the previous sequence and add the leading bit: [0,1,3,2,6,7,5,4]. Each boundary between halves still differs by exactly one bit.
Both approaches rely on properties of binary representation and concepts from math. The sequence length is always 2^n, so any correct algorithm must at least generate that many values.
Recommended for interviews: The bit manipulation formula i ^ (i >> 1) is the expected answer. It shows strong understanding of binary operations and generates the sequence with minimal logic. The recursive reflection approach demonstrates how Gray codes are constructed mathematically, which helps when interviewers want to test reasoning rather than memorization.
Gray code can be generated using a simple bit manipulation technique. For a given integer k, the corresponding Gray code is obtained by XORing k with (k >> 1). This technique ensures that each step in changing numbers results in transitioning only one bit.
This C program calculates Gray codes by iterating from 0 to 2n - 1, computing each Gray code number using i ^ (i >> 1) for each integer i.
Time complexity: O(2n), traversing all numbers.
Space complexity: O(1), using constant extra space.
The Gray code can be recursively generated by reflecting the existing sequence. Start with a base case of n=1: [0,1]. For each subsequent n, reflect the current list, prepend a bit to the reflected part, and concatenate the results: if Gn-1 = [0, 1], then Gn = [0Gn-1, 1Gn-1].
This C implementation uses recursion to build the Gray code sequence by reflecting and appending. Allocate memory for the result array and fill it with generated codes.
Time complexity: O(2n), where recursions reflect and build upon previous results.
Space complexity: O(2n), allocating for the result array.
Gray code is a type of encoding method that we often encounter in engineering. Its basic feature is that only one bit of binary number is different between any two adjacent codes.
The rule for converting binary code to binary Gray code is to keep the highest bit of the binary code as the highest bit of the Gray code, and the second highest bit of the Gray code is the XOR of the highest bit and the second highest bit of the binary code. The calculation of the remaining bits of the Gray code is similar to the second highest bit.
Assume that a binary number is represented as B_{n-1}B_{n-2}...B_2B_1B_0, and its Gray code is represented as G_{n-1}G_{n-2}...G_2G_1G_0. The highest bit is retained, so G_{n-1} = B_{n-1}; and the other bits G_i = B_{i+1} \oplus B_{i}, where i=0,1,2..,n-2.
Therefore, for an integer x, we can use the function gray(x) to get its Gray code:
int gray(x) {
return x ^ (x >> 1);
}
We directly map the integers [0,..2^n - 1] to the corresponding Gray codes to get the answer array.
The time complexity is O(2^n), where n is the integer given in the problem. Ignoring the space consumption of the answer, the space complexity is O(1).
Python
Java
C++
Go
JavaScript
| Approach | Complexity |
|---|---|
| Using Bit Manipulation | Time complexity: O(2n), traversing all numbers. |
| Recursive Gray Code Generation | Time complexity: O(2n), where recursions reflect and build upon previous results. |
| Binary to Gray Code Conversion | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Bit Manipulation Formula (i ^ (i >> 1)) | O(2^n) | O(1) auxiliary | Best for interviews and production. Simple iteration with minimal logic. |
| Recursive Reflection Construction | O(2^n) | O(2^n) | Useful to understand Gray code structure or when explaining the mathematical construction. |
Gray Code Explained using Recursion and Backtracking | Leetcode#89 Solution in JAVA • Pepcoding • 44,256 views views
Watch 9 more video solutions →Practice Gray Code with our built-in code editor and test cases.
Practice on FleetCode