The Wayback Machine - https://web.archive.org/web/20240726030157/https://www.geeksforgeeks.org/backtracking-approach-generate-n-bit-gray-codes/
Open In App

A backtracking approach to generate n bit Gray Codes

Last Updated : 05 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) 

Examples: 

Input : 2 
Output : 0 1 3 2
Explanation :
00 - 0
01 - 1
11 - 3
10 - 2

Input : 3
Output : 0 1 3 2 6 7 5 4

We have discussed an approach in Generate n-bit Gray Codes
This article provides a backtracking approach to the same problem. Idea is that for each bit out of n bit we have a choice either we can ignore it or we can invert the bit so this means our gray sequence goes upto 2 ^ n for n bits. So we make two recursive calls for either inverting the bit or leaving the bit as it is. 

C++




// CPP program to find the gray sequence of n bits.
#include <iostream>
#include <vector>
using namespace std;
 
/* we have 2 choices for each of the n bits either we
   can include i.e invert the bit or we can exclude the
   bit i.e we can leave the number as it is. */
void grayCodeUtil(vector<int>& res, int n, int& num)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0) {
        res.push_back(num);
        return;
    }
 
    // ignore the bit.
    grayCodeUtil(res, n - 1, num);
 
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1, num);
}
 
// returns the vector containing the gray
// code sequence of n bits.
vector<int> grayCodes(int n)
{
    vector<int> res;
 
    // num is passed by reference to keep
    // track of current code.
    int num = 0;
    grayCodeUtil(res, n, num);
 
    return res;
}
 
// Driver function.
int main()
{
    int n = 3;
    vector<int> code = grayCodes(n);
    for (int i = 0; i < code.size(); i++)
        cout << code[i] << endl;   
    return 0;
}


Java




// JAVA program to find the gray sequence of n bits.
import java.util.*;
 
class GFG
{
 
static int num;
 
/* we have 2 choices for each of the n bits either we
can include i.e invert the bit or we can exclude the
bit i.e we can leave the number as it is. */
static void grayCodeUtil(Vector<Integer> res, int n)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0)
    {
        res.add(num);
        return;
    }
 
    // ignore the bit.
    grayCodeUtil(res, n - 1);
 
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1);
}
 
// returns the vector containing the gray
// code sequence of n bits.
static Vector<Integer> grayCodes(int n)
{
    Vector<Integer> res = new Vector<Integer>();
 
    // num is passed by reference to keep
    // track of current code.
    num = 0;
    grayCodeUtil(res, n);
 
    return res;
}
 
// Driver function.
public static void main(String[] args)
{
    int n = 3;
    Vector<Integer> code = grayCodes(n);
    for (int i = 0; i < code.size(); i++)
        System.out.print(code.get(i) +"\n");
}
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to find the
# gray sequence of n bits.
 
""" we have 2 choices for each of the n bits
either we can include i.e invert the bit or
we can exclude the bit i.e we can leave
the number as it is. """
def grayCodeUtil(res, n, num):
     
    # base case when we run out bits to process
    # we simply include it in gray code sequence.
    if (n == 0):
        res.append(num[0])
        return
         
    # ignore the bit.
    grayCodeUtil(res, n - 1, num)
     
    # invert the bit.
    num[0] = num[0] ^ (1 << (n - 1))
    grayCodeUtil(res, n - 1, num)
     
# returns the vector containing the gray
# code sequence of n bits.
def grayCodes(n):
    res = []
     
    # num is passed by reference to keep
    # track of current code.
    num = [0]
    grayCodeUtil(res, n, num)
    return res
 
# Driver Code
n = 3
code = grayCodes(n)
for i in range(len(code)):
    print(code[i])
 
# This code is contributed by SHUBHAMSINGH10


C#




// C# program to find the gray sequence of n bits.
using System;
using System.Collections.Generic;
 
class GFG
{
 
static int num;
 
/* we have 2 choices for each of the n bits either we
can include i.e invert the bit or we can exclude the
bit i.e we can leave the number as it is. */
static void grayCodeUtil(List<int> res, int n)
{
    // base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0)
    {
        res.Add(num);
        return;
    }
 
    // ignore the bit.
    grayCodeUtil(res, n - 1);
 
    // invert the bit.
    num = num ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1);
}
 
// returns the vector containing the gray
// code sequence of n bits.
static List<int> grayCodes(int n)
{
    List<int> res = new List<int>();
 
    // num is passed by reference to keep
    // track of current code.
    num = 0;
    grayCodeUtil(res, n);
 
    return res;
}
 
// Driver function.
public static void Main(String[] args)
{
    int n = 3;
    List<int> code = grayCodes(n);
    for (int i = 0; i < code.Count; i++)
        Console.Write(code[i] +"\n");
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript program to find the gray sequence of n bits.
 
/* We have 2 choices for each of the n bits either we
can include i.e invert the bit or we can exclude the
bit i.e we can leave the number as it is. */
function grayCodeUtil(res, n, num)
{
     
    // Base case when we run out bits to process
    // we simply include it in gray code sequence.
    if (n == 0)
    {
        res.push(num[0]);
        return;
    }
 
    // Ignore the bit.
    grayCodeUtil(res, n - 1, num);
 
    // Invert the bit.
    num[0] = num[0] ^ (1 << (n - 1));
    grayCodeUtil(res, n - 1, num);
}
 
// Returns the vector containing the gray
// code sequence of n bits.
function grayCodes(n)
{
    let res = [];
 
    // num is passed by reference to keep
    // track of current code.
    let num = [0];
    grayCodeUtil(res, n, num);
 
    return res;
}
 
// Driver code
let n = 3;
let code = grayCodes(n);
for(let i = 0; i < code.length; i++)
    document.write(code[i] + "<br>");
     
// This code is contributed by gfgking
 
</script>


Output: 

0
1
3
2
6
7
5
4

Time Complexity: O(2n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Generate n-bit Gray Codes
Given a number N, generate bit patterns from 0 to 2^N-1 such that successive patterns differ by one bit. Examples: Input: N = 2 Output: 00 01 11 10 Input: N = 3 Output: 000 001 011 010 110 111 101 100 Method-1 The above sequences are Gray Codes of different widths. Following is an interesting pattern in Gray Codes.n-bit Gray Codes can be generated
14 min read
Gray to Binary and Binary to Gray conversion
Binary Number is the default way to store numbers, but in many applications, binary numbers are difficult to use and a variety of binary numbers is needed. This is where Gray codes are very useful. Gray code has a property that two successive numbers differ in only one bit because of this property gray code does the cycling through various states w
13 min read
Generate all distinct subsequences of array using backtracking
Given an array arr[] consisting of N positive integers, the task is to generate all distinct subsequences of the array. Examples: Input: arr[] = {1, 2, 2}Output: {} {1} {1, 2} {1, 2, 2} {2} {2, 2}Explanation:The total subsequences of the given array are {}, {1}, {2}, {2}, {1, 2}, {1, 2}, {2, 2}, {1, 2, 2}.Since {2} and {1, 2} are repeated twice, pr
7 min read
Linde-Buzo-Gray (LBG) Algorithm
Linde-Buzo-Gray (LBG) Algorithm is used for designing of Codebook efficiently which has minimum distortion and error. LBG algorithm was proposed by Yoseph Linde, Andres Buzo and Robert M. Gray in 1980. It is the most common algorithm for Code Generation that generates a codebook with minimum error from a training set. Training sets are a set of vec
2 min read
Binary to Gray code using recursion
Given the Binary code of a number as a decimal number, we need to convert this into its equivalent Gray Code. Assume that the binary number is in the range of integers. For the larger value, we can take a binary number as string. In gray code, only one bit is changed in 2 consecutive numbers. Examples: Input: 1001 Output: 1101Explanation: 1001 -
5 min read
Decimal Equivalent of Gray Code and its Inverse
Given a decimal number n. Find the gray code of this number in decimal form. Examples: Input : 7 Output : 4 Explanation: 7 is represented as 111 in binary form. The equivalent gray code of 111 is 100 in binary form, whose decimal equivalent is 4. Input : 10 Output : 15 Explanation: 10 is represented as 1010 in binary form. The equivalent gray code
7 min read
CSES Solutions - Gray Code
A Gray code is a list of all 2n bit strings of length n, where any two successive strings differ in exactly one bit (i.e., their Hamming distance is one). Your task is to create a Gray code for a given length n. Examples: Input: n=2Output: {"00", "01", "11", "10"} Input: n=1Output: {"0", "1"} Approach: Follow the below approach to solve the problem
5 min read
Code Converters - Binary to/from Gray Code
In this article, we will go through Code Converters - Binary to/from Gray Code,we will start our article by defining Code converters, Binary code and Gray code, and then we will go through the conversion of binary code to gray code and vice versa. At last, we will conclude our article with some faqs. Table of Content Code ConvertersBinary CodeGray
9 min read
Inserting M into N such that m starts at bit j and ends at bit i | Set-2
Given two 32-bit numbers, N and M, and two-bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. Assuming index start from 0.Examples: a) N = 1024 (10000000000), M = 19 (10011), i = 2, j = 6 Output : 1100 (10001001100) b) N
10 min read
Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string is always valid.Examples: Input: str = "11100" Ou
4 min read
Practice Tags :
three90RightbarBannerImg