The problem is to generate a sequence of Gray codes for a given number n
.
Gray code is a binary numeral system where two successive values differ in only one bit.
For a given integer n
, generate the sequence of 2^n
Gray codes. A Gray code sequence must begin with 0.
For n = 2
, the Gray code sequence is [0, 1, 3, 2]
. Note that:
0
in binary is 00
1
in binary is 01
3
in binary is 11
2
in binary is 10
where consecutive numbers differ by only one bit.To generate Gray codes for a given integer n
, we can use the following approach:
i
(where 0 <= i < 2^n
), the i-th Gray code can be obtained by using the formula:
gray(i) = i ^ (i >> 1)
Here, ^
denotes the bitwise XOR operator, and >>
denotes right shift.
Let’s implement the solution in C++:
#include <vector>
class Solution {
public:
std::vector<int> grayCode(int n) {
std::vector<int> result;
int totalNumbers = 1 << n; // 2^n
for (int i = 0; i < totalNumbers; ++i) {
result.push_back(i ^ (i >> 1));
}
return result;
}
};
result
to store the Gray codes.n
bits is 2^n
, which is computed using 1 << n
.i
from 0
to 2^n - 1
, compute the Gray code using the formula i ^ (i >> 1)
.result
vector.result
vector containing the Gray codes.The time complexity of this approach is O(2^n). This is because we generate 2^n
Gray codes, and each operation inside the loop (bitwise XOR and right shift) takes constant time, O(1). Hence, the overall time complexity is O(2^n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?