Given an integer n, generate all n-bit Gray codes. A Gray code sequence starts with n zeros, and every consecutive code in the sequence differs from the previous one by exactly one bit.
Examples:
Input: n = 2
Output: ["00", "01", "11", "10"]
Explanation: The sequence starts with 00. Every consecutive pair of codes differs by exactly one bit.Input: n = 3
Output: ["000", "001", "011", "010", "110", "111", "101", "100"]
Explanation: The sequence starts with 000, and every consecutive pair of codes differs by exactly one bit.
Table of Content
Using Reflection Method - O(n*(2^n)) Time and O(n*(2^n)) Space
The idea is based on the fact that an n-bit Gray code sequence can be generated from an (n - 1)-bit Gray code sequence. We start with the 1-bit Gray code sequence {"0", "1"}.
For each new bit position, we first copy the current Gray code sequence in reverse order and append it to the original sequence. Then, we prefix 0 to all codes in the first half and prefix 1 to all codes in the second half. The resulting sequence forms the Gray codes of the next length.
To generate 3-bit Gray codes from 2-bit Gray codes:
- The 2-bit Gray code sequence is: 00 01 11 10
- Copy the sequence in reverse order: 10 11 01 00
- Add prefix 0 to the original sequence: 000 001 011 010
- Add prefix 1 to the reversed sequence: 110 111 101 100
Combining both sequences gives 3- bit Gray codes: 000 001 011 010 110 111 101 100
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> generateGrayCodes(int n) {
vector<string> res;
// base case
res.push_back("0");
res.push_back("1");
for (int i = 2; i <= n; i++) {
int size = res.size();
// reverse and append
for (int j = size - 1; j >= 0; j--) {
res.push_back(res[j]);
}
// add '0' to first half
for (int j = 0; j < size; j++) {
res[j] = "0" + res[j];
}
// add '1' to second half
for (int j = size; j < 2 * size; j++) {
res[j] = "1" + res[j];
}
}
return res;
}
int main() {
int n = 3;
vector<string> res = generateGrayCodes(n);
cout << "[";
for (int i = 0; i < res.size(); i++) {
cout << res[i];
if (i < res.size() - 1)
cout << ", ";
}
cout << "]\n";
return 0;
}
import java.util.ArrayList;
class GFG {
public static ArrayList<String> generateGrayCodes(int n) {
ArrayList<String> res = new ArrayList<>();
res.add("0");
res.add("1");
for (int i = 2; i <= n; i++) {
int size = res.size();
// reverse and append
for (int j = size - 1; j >= 0; j--) {
res.add(res.get(j));
}
// prefix '0'
for (int j = 0; j < size; j++) {
res.set(j, "0" + res.get(j));
}
// prefix '1'
for (int j = size; j < 2 * size; j++) {
res.set(j, "1" + res.get(j));
}
}
return res;
}
public static void main(String[] args) {
int n = 3;
ArrayList<String> res = generateGrayCodes(n);
System.out.print(res);
}
}
def generateGrayCodes(n):
res = ["0", "1"]
for i in range(2, n + 1):
size = len(res)
# reverse and append
res += res[::-1]
# prefix '0'
for j in range(size):
res[j] = "0" + res[j]
# prefix '1'
for j in range(size, 2 * size):
res[j] = "1" + res[j]
return res
if __name__ == "__main__":
n = 3
res = generateGrayCodes(n)
print("[" + ", ".join(res) + "]")
using System;
using System.Collections.Generic;
class GFG {
static List<string> generateGrayCodes(int n)
{
List<string> res = new List<string>();
res.Add("0");
res.Add("1");
for (int i = 2; i <= n; i++) {
int size = res.Count;
// reverse and append
for (int j = size - 1; j >= 0; j--) {
res.Add(res[j]);
}
// prefix '0'
for (int j = 0; j < size; j++) {
res[j] = "0" + res[j];
}
// prefix '1'
for (int j = size; j < 2 * size; j++) {
res[j] = "1" + res[j];
}
}
return res;
}
static void Main()
{
int n = 3;
List<string> res = generateGrayCodes(n);
Console.Write("[");
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i]);
if (i < res.Count - 1) {
Console.Write(", ");
}
}
Console.WriteLine("]");
}
}
function generateGrayCodes(n) {
let res = ["0", "1"];
for (let i = 2; i <= n; i++) {
let size = res.length;
// reverse and append
for (let j = size - 1; j >= 0; j--) {
res.push(res[j]);
}
// prefix '0'
for (let j = 0; j < size; j++) {
res[j] = "0" + res[j];
}
// prefix '1'
for (let j = size; j < 2 * size; j++) {
res[j] = "1" + res[j];
}
}
return res;
}
// Driver Code
let n = 3;
let res = generateGrayCodes(n);
process.stdout.write("[");
for (let i = 0; i < res.length; i++) {
process.stdout.write(res[i]);
if (i < res.length - 1) {
process.stdout.write(", ");
}
}
console.log("]");
Output
[000, 001, 011, 010, 110, 111, 101, 100]
Using Bit Manipulation - O(n*(2^n)) Time and O(n*(2^n)) Space
The idea is to generate the i-th Gray code directly using the formula:
Gray(i) = i ^ (i >> 1) , where ^ represents the bitwise XOR operator.
We iterate through all numbers from 0 to 2^n - 1 and compute the corresponding Gray code using the above formula. Each generated Gray code is then converted into an n-bit binary string and added to the result.
For n = 3, we generate the Gray codes by iterating from 0 to 2^3 - 1 = 7 and applying the formula: Gray(i) = i ^ (i >> 1)
The generated Gray codes are:
- Gray(0) = 0 ^ 0 = 0 -> 000
- Gray(1) = 1 ^ 0 = 1 -> 001
- Gray(2) = 2 ^ 1 = 3 -> 011
- Gray(3) = 3 ^ 1 = 2 -> 010
- Gray(4) = 4 ^ 2 = 6 -> 110
- Gray(5) = 5 ^ 2 = 7 -> 111
- Gray(6) = 6 ^ 3 = 5 -> 101
- Gray(7) = 7 ^ 3 = 4 -> 100
Thus, the generated 3-bit Gray code sequence is: 000 001 011 010 110 111 101 100
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> generateGrayCodes(int n) {
vector<string> res;
for (int i = 0; i < (1 << n); i++) {
// generate i-th Gray code
int g = i ^ (i >> 1);
// Convert the code to string
string s = "";
for (int j = n - 1; j >= 0; j--) {
if (g & (1 << j))
s += '1';
else
s += '0';
}
res.push_back(s);
}
return res;
}
int main() {
int n = 3;
vector<string> res = generateGrayCodes(n);
cout << "[";
for (int i = 0; i < res.size(); i++) {
cout << res[i];
if (i < res.size() - 1)
cout << ", ";
}
cout << "]\n";
return 0;
}
import java.util.ArrayList;
class GFG {
public static ArrayList<String> generateGrayCodes(int n) {
ArrayList<String> res = new ArrayList<>();
for (int i = 0; i < (1 << n); i++) {
// generate i-th Gray code
int g = i ^ (i >> 1);
// Convert the code to string
StringBuilder sb = new StringBuilder();
for (int j = n - 1; j >= 0; j--) {
if ((g & (1 << j)) != 0)
sb.append('1');
else
sb.append('0');
}
res.add(sb.toString());
}
return res;
}
public static void main(String[] args) {
int n = 3;
ArrayList<String> res = generateGrayCodes(n);
System.out.print(res);
}
}
def generateGrayCodes(n):
res = []
for i in range(1 << n):
# generate i-th Gray code
g = i ^ (i >> 1)
# Convert the code to string
s = ""
for j in range(n - 1, -1, -1):
if g & (1 << j):
s += "1"
else:
s += "0"
res.append(s)
return res
if __name__ == "__main__":
n = 3
res = generateGrayCodes(n)
print("[", end="")
for i in range(len(res)):
print(res[i], end="")
if i < len(res) - 1:
print(", ", end="")
print("]")
using System;
using System.Collections.Generic;
class GFG {
static List<string> generateGrayCodes(int n)
{
List<string> res = new List<string>();
for (int i = 0; i < (1 << n); i++) {
// generate i-th Gray code
int g = i ^ (i >> 1);
// Convert the code to string
string s = "";
for (int j = n - 1; j >= 0; j--) {
if ((g & (1 << j)) != 0)
s += "1";
else
s += "0";
}
res.Add(s);
}
return res;
}
static void Main()
{
int n = 3;
List<string> res = generateGrayCodes(n);
Console.Write("[");
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i]);
if (i < res.Count - 1) {
Console.Write(", ");
}
}
Console.WriteLine("]");
}
}
function generateGrayCodes(n) {
let res = [];
for (let i = 0; i < (1 << n); i++) {
// generate i-th Gray code
let g = i ^ (i >> 1);
// Convert the code to string
let s = "";
for (let j = n - 1; j >= 0; j--) {
if (g & (1 << j))
s += "1";
else
s += "0";
}
res.push(s);
}
return res;
}
// Driver Code
let n = 3;
let res = generateGrayCodes(n);
process.stdout.write("[");
for (let i = 0; i < res.length; i++) {
process.stdout.write(res[i]);
if (i < res.length - 1) {
process.stdout.write(", ");
}
}
console.log("]");
Output
[000, 001, 011, 010, 110, 111, 101, 100]