CSES Solutions Gray Code (original) (raw)

Last Updated : 23 Jul, 2025

A Gray code is a list of all 2 n bit strings of length **n, where any two successive strings differ in exactly one bit (i.e., their Hamming distance is one).

The task is to create a Gray code for a given length **n.

**Examples:

**Input: n=2
**Output: ["00", "01", "11", "10"]

**Input: n=1
**Output: ["0", "1"]

**Input: n=3
**Output: ["000", "001", "011", "010", "110", "111", "101", "100"]

Table of Content

**Recursive Approach - O(2^n) time and O(2^n) space

The idea is to solve the problem recursively.

We have to generate list of 2n binary strings where any two successive strings differ in exactly one bit. Now suppose we know the answer for n-1, i.e., we are able to generate 2n-1 binary strings. To extend this list to 2n binary string we first store the list of 2n-1 binary strings temporarly and reverse the order of the strings. Next, we prepend '0' to each string in the original list and '1' to each string in the reversed list. Finally, we concatenate these modified lists to obtain the Gray code for length n. Let's consider the example

**Follow the steps to solve the problem:

**Below is the implementation of above approach:

C++ `

// C++ program to generate bit patterns from 0 to 2^N-1 #include <bits/stdc++.h> using namespace std;

vector graycode(int n) {

// Base Case 
if (n == 1) {
    return {"0", "1"};
}

// Calculate the strings for n-1 length 
vector<string> prevGrayCode = graycode(n - 1);
  
// Reverse the previous Gray Code for n-1 length
vector<string> reversedPrevGrayCode = prevGrayCode;
reverse(reversedPrevGrayCode.begin(), reversedPrevGrayCode.end());

int prevSize = prevGrayCode.size();
int index = 0;
while (index < prevSize) {
    
    // Prepend the character 0 in previous Gray Codes
    string appendedZero = "0" + prevGrayCode[index];

    // Prepend the character 1 in Reversed previous Gray Codes
    prevGrayCode[index] = "1" + reversedPrevGrayCode[index];
    prevGrayCode.push_back(appendedZero);
    index++;
}
return prevGrayCode;

}

int main() { int n = 2; vector res = graycode(n); for (auto code : res) cout << code << "\n"; return 0; }

Java

// Java program to generate bit patterns from 0 to 2^N-1

import java.util.ArrayList; import java.util.Collections;

class GfG {

static ArrayList<String> graycode(int n) {
    
    // Base Case 
    if (n == 1) {
        ArrayList<String> base = new ArrayList<>();
        base.add("0");
        base.add("1");
        return base;
    }
  
    // Calculate the strings for n-1 length 
    ArrayList<String> prevGrayCode = graycode(n - 1);
      
    // Reverse the previous Gray Code for n-1 length
    ArrayList<String> reversedPrevGrayCode = new ArrayList<>(prevGrayCode);
    Collections.reverse(reversedPrevGrayCode);
  
    int prevSize = prevGrayCode.size();
    int index = 0;
    while (index < prevSize) {
        
        // Prepend the character 0 in previous Gray Codes
        String appendedZero = "0" + prevGrayCode.get(index);
   
        // Prepend the character 1 in Reversed previous Gray Codes
        prevGrayCode.set(index, "1" + reversedPrevGrayCode.get(index));
        prevGrayCode.add(appendedZero);
        index++;
    }
    return prevGrayCode;
}

public static void main(String[] args) {
    int n = 2;
    ArrayList<String> res = graycode(n);
    for (String code : res) {
        System.out.println(code);
    }
}

}

Python

Python program to generate bit patterns from 0 to 2^N-1

def graycode(n):

# Base Case 
if n == 1:
    return ["0", "1"]

# Calculate the strings for n-1 length 
prevGrayCode = graycode(n - 1)
  
# Reverse the previous Gray Code for n-1 length
reversedPrevGrayCode = prevGrayCode[::-1]

prevSize = len(prevGrayCode)
index = 0
while index < prevSize:
    
    # Prepend the character 0 in previous Gray Codes
    appendedZero = "0" + prevGrayCode[index]

    # Prepend the character 1 in Reversed previous Gray Codes
    prevGrayCode[index] = "1" + reversedPrevGrayCode[index]
    prevGrayCode.append(appendedZero)
    index += 1

return prevGrayCode

if name == "main": n = 2 res = graycode(n) for code in res: print(code)

C#

// C# program to generate bit patterns from 0 to 2^N-1

using System; using System.Collections.Generic;

class GfG {

static List<string> graycode(int n) {
    
    // Base Case 
    if (n == 1) {
        return new List<string> { "0", "1" };
    }
  
    // Calculate the strings for n-1 length 
    List<string> prevGrayCode = graycode(n - 1);
      
    // Reverse the previous Gray Code for n-1 length
    List<string> reversedPrevGrayCode = new List<string>(prevGrayCode);
    reversedPrevGrayCode.Reverse();
  
    int prevSize = prevGrayCode.Count;
    int index = 0;
    while (index < prevSize) {
        
        // Prepend the character 0 in previous Gray Codes
        string appendedZero = "0" + prevGrayCode[index];
   
        // Prepend the character 1 in Reversed previous Gray Codes
        prevGrayCode[index] = "1" + reversedPrevGrayCode[index];
        prevGrayCode.Add(appendedZero);
        index++;
    }
    return prevGrayCode;
}

static void Main() {
    int n = 2;
    List<string> res = graycode(n);
    foreach (string code in res) {
        Console.WriteLine(code);
    }
}

}

JavaScript

// JavaScript program to generate bit patterns from 0 to 2^N-1

function graycode(n) {

// Base Case 
if (n === 1) {
    return ["0", "1"];
}

// Calculate the strings for n-1 length 
let prevGrayCode = graycode(n - 1);
  
// Reverse the previous Gray Code for n-1 length
let reversedPrevGrayCode = [...prevGrayCode].reverse();

let prevSize = prevGrayCode.length;
let index = 0;
while (index < prevSize) {
    
    // Prepend the character 0 in previous Gray Codes
    let appendedZero = "0" + prevGrayCode[index];

    // Prepend the character 1 in Reversed previous Gray Codes
    prevGrayCode[index] = "1" + reversedPrevGrayCode[index];
    prevGrayCode.push(appendedZero);
    index++;
}
return prevGrayCode;

}

// Driver Code let n = 2; let res = graycode(n); for (let code of res) { console.log(code); }

`

**Time Complexity: O(2n), as we have to generate 2^n strings.
**Auxilary Space: O(2n), due to resultant array.

Iterative Approach (Using property of XOR) - O(n*(2^n)) time and O(2^n) space

The idea is to use the mathematical property that a binary number's Gray code can be obtained by **XORing the number with itself shifted right by one position (i.e., n ^ (n>>1)).

C++ `

// C++ program to generate bit patterns from 0 to 2^N-1 #include <bits/stdc++.h> using namespace std;

vector graycode(int n) { vector result;

// Do for all binary numbers
for(int i = 0; i < (1 << n); i++) {
    int gray = i ^ (i >> 1);
    string code = "";
    for(int j = n-1; j >= 0; j--) {
        code += (gray & (1 << j)) ? '1' : '0';
    }
    result.push_back(code);
}
return result;

}

int main() { int n = 2; vector res = graycode(n); for(string code : res) { cout << code << endl; } return 0; }

Java

// Java program to generate bit patterns from 0 to 2^N-1

import java.util.ArrayList;

class GfG {

static ArrayList<String> graycode(int n) {
    ArrayList<String> result = new ArrayList<>();
    
    // Do for all binary numbers
    for(int i = 0; i < (1 << n); i++) {
        int gray = i ^ (i >> 1);
        String code = "";
        for(int j = n - 1; j >= 0; j--) {
            code += (gray & (1 << j)) != 0 ? '1' : '0';
        }
        result.add(code);
    }
    return result;
}

public static void main(String[] args) {
    int n = 2;
    ArrayList<String> res = graycode(n);
    for(String code : res) {
        System.out.println(code);
    }
}

}

Python

Python program to generate bit patterns from 0 to 2^N-1

def graycode(n): result = []

# Do for all binary numbers
for i in range(1 << n):
    gray = i ^ (i >> 1)
    code = ""
    for j in range(n - 1, -1, -1):
        code += '1' if (gray & (1 << j)) else '0'
    result.append(code)

return result

if name == "main": n = 2 res = graycode(n) for code in res: print(code)

C#

// C# program to generate bit patterns from 0 to 2^N-1

using System; using System.Collections.Generic;

class GfG {

static List<string> graycode(int n) {
    List<string> result = new List<string>();
    
    // Do for all binary numbers
    for(int i = 0; i < (1 << n); i++) {
        int gray = i ^ (i >> 1);
        string code = "";
        for(int j = n - 1; j >= 0; j--) {
            code += (gray & (1 << j)) != 0 ? '1' : '0';
        }
        result.Add(code);
    }
    return result;
}

static void Main() {
    int n = 2;
    List<string> res = graycode(n);
    foreach(string code in res) {
        Console.WriteLine(code);
    }
}

}

JavaScript

// JavaScript program to generate bit patterns from 0 to 2^N-1

function graycode(n) { let result = [];

// Do for all binary numbers
for(let i = 0; i < (1 << n); i++) {
    let gray = i ^ (i >> 1);
    let code = "";
    for(let j = n - 1; j >= 0; j--) {
        code += (gray & (1 << j)) ? '1' : '0';
    }
    result.push(code);
}
return result;

}

// Driver Code let n = 2; let res = graycode(n); for(let code of res) { console.log(code); }

`

Time Complexity: O(n*(2^n)), to generate all binary numbers and convert the binary number into string.
**Auxiliary Space: O(2^n),to store the resultant array.