Generate Grey Code Sequences | Practice | GeeksforGeeks

Given a number N, your task is to complete the function which generates all n-bit grey code sequences, a grey code sequence is a sequence such that successive patterns in it differ by one bit.
Example 1:
Input:
N = 2
Output: 00 01 11 10
Explanation: All 2-bit gray codes are
00, 01, 11, 10 such that successive
patterns in it differ by one bit.

Example 2:
Input:
N = 1
Output: 0 1
 
Your Task:
Complete the function generateCode() which takes an integer as input parameter and retruns an array of all N bit grey code sequence such that successive patterns in it differ by one bit.
Expected Time Complexity: O(N * 2N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 16
0
vishnu12654 days ago
ArrayList<String> res = new ArrayList<String>();
    
    void greyCode(String s , int value , int level , int n){
        if(level == n){
            res.add(s);
            return;
        }
        if(value == 0){
            greyCode(s+"0",0,level+1,n);
            greyCode(s+"1",1,level+1,n);
        }
        else if(value == 1){
            greyCode(s+"1",0,level+1,n);
            greyCode(s+"0",1,level+1,n);
        }
    }
    
    ArrayList <String> generateCode(int n)
    {
	    if(res.isEmpty()==false){
	        res.clear();
	    }
	    greyCode("",0,0,n);
	    return res;
	    
    }
0
awektoppo2 weeks ago
 void getCode(int N,int pos,vector<string>& ans){    if(N==pos){        return;    }    vector<string> L1(ans.size()),L2(ans.size());    for(int i=0;i<ans.size();i++){        L1[i] ='0' + ans[i];        L2[i] = '1'+ans[ans.size()-i-1];    }    for(int i=0;i<L1.size();i++){        ans[i]=L1[i];    }    for(int i=0;i<L2.size();i++){       ans.push_back(L2[i]);    }    getCode(N,pos+1,ans);     }    vector <string> generateCode(int N)   {        //Your code here        string s="";        vector<string> ans={"0","1"};        getCode(N,1,ans);   return ans;          }
0
geminicode3 months ago
is it compulsory to print the answer in the same sequence as given in the description? isn't 00 01 and 00 10 both correct ?? can anyone explain ?
 
0
pramodpawarkp3 months ago
//time 0.3/1.4
 string str_make(int i)  //fuction for dec to bin  {      string s="";      while(i)      {          s+=i%2+'0';          i/=2;      }      return s;  }   vector <string> generateCode(int N)   {       vector<string>ans;        int count=pow(2,N);        int i=0;        while(i<count)        {            int gray=i^(i>>1);  //gray conversion            string temp=str_make(gray);  //function for dec to bin            if(temp.length()<N)            {                int k=N-temp.length();                while(k--)                {                    temp.push_back('0');                }            }            reverse(temp.begin(),temp.end());            ans.push_back(temp);            i++;        }        return ans;   }
0
amukherjee98am3 months ago
//CPP solution
//Time taken 0.3
class Solution{
  public:
        
        vector <string> generateCode(int N)
        {
            //Your code here
            vector<string> v;
            if(N<1)
                return v;
            v.push_back("0");
            v.push_back("1");
            if(N==1)
                return v;
            for(int i=2;i<=N;i++)
            {
                for(int j=0;j<pow(2,i-1);j++)
                {
                    v.push_back(v[pow(2,i-1)-1-j]);
                }
                for(int j=0;j<pow(2,i);j++)
                {
                    if(j<pow(2,i-1))
                    {
                        v[j]='0'+v[j];
                    }
                    else
                    {
                        v[j]='1'+v[j];
                    }
                }
            }
            return v;
        }
};
-1
chessnoobdj4 months ago
Iterative c++
vector <string> generateCode(int N)
    {
        vector <string> res;
        int num = pow(2, N);
        for(int i=0; i<num; i++){
            string str = "";
            int gray = i^(i>>1);
            str = bitset<16>(gray).to_string();
            str = str.substr(16-N, N);
            res.push_back(str);
        }
        return res;
    }
0
kronizerdeltac4 months ago
JAVA RECURSIVE SOLUTION
class Solution{   ArrayList <String> generateCode(int n)   {       if(n == 1) {           ArrayList <String> base = new ArrayList<>();           base.add("0");           base.add("1");           return base;       }              ArrayList <String> ans = generateCode(n - 1);       ArrayList <String> myAns = new ArrayList<>();       for(int i = 0; i < ans.size(); i++) {           myAns.add("0" + ans.get(i));       }              for(int i = ans.size() - 1; i >= 0; i--) {           myAns.add("1" + ans.get(i));       }              return myAns;   }}
0
uav21122projects6 months ago
//C approach 

int grayCode(int n)
{
    return (n ^ n>>1);
}

void decToBinary(int n, int r){

    for(int i=r-1; i>=0; i--)
        (n & (1<<i)) ? printf("1") : printf("0");

    //printf("\n");
}

int generateCode(int n)
{
    int a = 0;
    for (int i = 0; i < 2*n; i++)
    {
        a = grayCode(i);
        decToBinary(a, n);
        printf(" ");
    }
    
}
0
rohitshah4083
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.