← Home

89. Gray Code

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
bit manipulationC++Markdown
89

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 89. Gray Code, the solution in this repository is mainly a bit manipulation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: bit manipulation, backtracking.

The notes already sitting in the source point us in the right direction:

  • backtracking
  • TLE
  • 4 / 12 test cases passed.
  • testcase: 4

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are backtrack, grayCode, used, diffByOneBit.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//backtracking
02//TLE
03//4 / 12 test cases passed.
04//testcase: 4
05class Solution {
06public:
07    int n;
08    vector<int> ans;
09    
10    void backtrack(vector<int>& perm, vector<bool>& used){
11        if(all_of(used.begin(), used.end(), [](const bool& b){return b;})){
12            bool valid = true;
13            for(int i = 0; i+1 < n; ++i){
14                if(__builtin_popcount(perm[i]^perm[i+1]) != 1){
15                    valid = false;
16                    break;
17                }
18            }
19            if(valid){
20                ans = perm;
21            }
22        }else{
23            for(int i = 0; i < n; ++i){
24                if(used[i]) continue;
25                perm.push_back(i);
26                used[i] = true;
27                backtrack(perm, used);
28                if(!ans.empty()) return;
29                perm.pop_back();
30                used[i] = false;
31            }
32        }
33    }
34    
35    vector<int> grayCode(int n) {
36        this->n = 1<<n;
37        vector<int> perm;
38        vector<bool> used(1<<n, false);
39        backtrack(perm, used);
40        return ans;
41    }
42};
43
44//speed up from above
45//6 / 12 test cases passed.
46//testcase: 10
47class Solution {
48public:
49    int n;
50    vector<int> ans;
51    
52    void backtrack(vector<int>& perm, vector<bool>& used){
53        if(all_of(used.begin(), used.end(), [](const bool& b){return b;})){
54            bool valid = true;
55            // for(int i = 0; i+1 < n; ++i){
56            //     if(__builtin_popcount(perm[i]^perm[i+1]) != 1){
57            //         valid = false;
58            //         break;
59            //     }
60            // }
61            if(valid){
62                ans = perm;
63            }
64        }else{
65            for(int i = 0; i < n; ++i){
66                if(used[i]) continue;
67                if(!perm.empty() && 
68                   __builtin_popcount(perm.back()^i) != 1) continue;
69                perm.push_back(i);
70                used[i] = true;
71                backtrack(perm, used);
72                if(!ans.empty()) return;
73                perm.pop_back();
74                used[i] = false;
75            }
76        }
77    }
78    
79    vector<int> grayCode(int n) {
80        this->n = 1<<n;
81        vector<int> perm;
82        vector<bool> used(1<<n, false);
83        backtrack(perm, used);
84        return ans;
85    }
86};
87
88//backtracking, faster
89//https://leetcode.com/problems/gray-code/discuss/400651/Java-Solutions-with-Detailed-Comments-and-Explanations-(Backtracking-Prepending)
90//Runtime: 4 ms, faster than 25.43% of C++ online submissions for Gray Code.
91//Memory Usage: 7.8 MB, less than 6.92% of C++ online submissions for Gray Code.
92class Solution {
93public:
94    int p2n, n;
95    vector<int> ans;
96    
97    bool diffByOneBit(int a, int b){
98        int x = a^b;
99        
100        //x==0 <-> a==b
101        //x&(x-1): remove x's last bit
102        //((x&(x-1)) == 0): x has only one digit
103        
104        return (x!=0) && ((x&(x-1)) == 0);
105    }
106    
107    void backtrack(vector<int>& res, vector<bool>& used){
108        if(res.size() == p2n){
109            if(diffByOneBit(res[0], res.back())){
110                ans = res;
111            }
112        }else{
113            const int last = res.back();
114            for(int i = 0; i < n; ++i){
115                int cur = last ^ (1<<i);
116                if(used[cur]) continue;
117                res.push_back(cur);
118                used[cur] = true;
119                backtrack(res, used);
120                if(!ans.empty()) return;
121                res.pop_back();
122                used[cur] = false;
123            }
124        }
125    }
126    
127    vector<int> grayCode(int n) {
128        if(n == 0) return {0};
129        this->n = n;
130        this->p2n = (1<<n);
131        
132        vector<int> res;
133        vector<bool> used(this->p2n, false);
134        
135        res = {0};
136        used[0] = true;
137        
138        backtrack(res, used);
139        
140        return ans;
141    }
142};
143
144//iterative
145//https://leetcode.com/problems/gray-code/discuss/400651/Java-Solutions-with-Detailed-Comments-and-Explanations-(Backtracking-Prepending)
146//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Gray Code.
147//Memory Usage: 6.7 MB, less than 48.06% of C++ online submissions for Gray Code.
148class Solution {
149public:
150    vector<int> grayCode(int n) {
151        vector<int> res = {0};
152        
153        for(int i = 0; i < n; ++i){
154            /*
155            in ith iteration, 
156            we change res of size 1<<i to
157            res of size 1<<(i+1)
158            
159            in ith iteration,
160            the range of res is [0,1<<(i+1)),
161            we already have range [0,1<<i),
162            now we need to add range[1<<i,1<<(i+1)),
163            and we can create it by 
164            adding 1<<i to the old range
165            */
166            int prependVal = 1 << i;
167            int oldSize = res.size();
168            //double the size of res
169            for(int j = oldSize-1; j >= 0; --j){
170                res.push_back(prependVal + res[j]);
171            }
172            /*
173            the numbers in the later half all diff by one bit,
174            because they are created from the old res
175            
176            res[oldSize-1] and res[oldSize] diff by one bit
177            (the most significant bit)
178            
179            res[newSize-1] and res[0] diff by one bit
180            (the most significant bit)
181            */
182        }
183        
184        return res;
185    }
186};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.