Gray Code


Problem Statement :


An n-bit gray code sequence is a sequence of 2n integers where:

Every integer is in the inclusive range [0, 2n - 1],
The first integer is 0,
An integer appears no more than once in the sequence,
The binary representation of every pair of adjacent integers differs by exactly one bit, and
The binary representation of the first and last integers differs by exactly one bit.
Given an integer n, return any valid n-bit gray code sequence.

 

Example 1:

Input: n = 2
Output: [0,1,3,2]
Explanation:
The binary representation of [0,1,3,2] is [00,01,11,10].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit
Example 2:

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

Constraints:

1 <= n <= 16



Solution :



title-img


                            Solution in C :

int* grayCode(int n, int* len) {
    *len=1<<n;
    int *ret = malloc(sizeof(*ret)**len);
    ret[0]=0;
    int nn=1;
    while(n--){
        for (int i=0;i<nn;i++){
            ret[nn+i]=nn|ret[nn-i-1];
        }
        nn<<=1;
    }
    return ret;
}
                        


                        Solution in C++ :

class Solution {
public:
    vector<int> grayCode(int n) {
        
        int iteration = 1;
        int fac = 1;
        vector<int> result{0, 1};

        for( ; iteration < n ; iteration++ ){
            fac = fac*2;
            int l = result.size()-1;
            for( ; l>=0 ; l-- ){
                int val = result[l] + fac;
                result.push_back(val);
            }
        }

        return result;
    }
};
                    


                        Solution in Java :

class Solution {
    List<Integer> ans;
    HashSet<String> visited;
    public List<Integer> grayCode(int n) {
        visited = new HashSet();
        ans = new ArrayList();
        StringBuilder s = new StringBuilder();
        for(int i=0;i<n;i++)
          s.append('0');
        dfs(s,n);
        return ans;
    }
    void dfs(StringBuilder s,  int n)
    {
        if(visited.contains(s.toString()))
            return;
        visited.add(s.toString());
        ans.add(Integer.parseInt(s.toString(),2));
        for(int i=0;i<n;i++)
        {
           char or = s.charAt(i);
           char c = (or=='0')?'1': '0';
            s.setCharAt(i,c);
            if(!visited.contains(c))
                dfs(s,n);
            s.setCharAt(i,or);
        }
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def grayCode(self, n: int) -> List[int]:
        oldArr = [0,1]
        i = 1
        while i< n:
            Arr = list(oldArr)
            for j in range(len(oldArr)-1,-1,-1):
                Arr.append((2**i)+oldArr[j])
            oldArr = Arr
            i+=1
        return oldArr
                    


View More Similar Problems

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →