89. Gray Code
Problem
Return an n-bit Gray code: a sequence of all 2ⁿ integers in [0, 2ⁿ − 1], starting at 0, in which consecutive values (including the last and the first) differ in exactly one bit. Any valid sequence is accepted.
Example: n = 2 → [0,1,3,2]
Constraints: n ≤ 16.
The i-th Gray code is i ^ (i >> 1): consecutive values differ in exactly one bit, and the sequence wraps around.
i 000 001 010 011 100 101 110 111
gray 000 001 011 010 110 111 101 100
Complexity: O(2ⁿ).
class Solution:
def grayCode(self, n: int) -> List[int]:
return [i ^ (i >> 1) for i in range(1 << n)]
# any valid Gray code: starts at 0, visits all 2^n values once, neighbours (incl. wrap-around) differ by one bit
for n in (1, 2, 3, 4):
g = Solution().grayCode(n)
assert g[0] == 0 and sorted(g) == list(range(1 << n))
assert all(bin(g[i] ^ g[(i + 1) % len(g)]).count("1") == 1 for i in range(len(g)))
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < 1 << n; i++) res.add(i ^ (i >> 1));
return res;
}
}
func grayCode(n int) []int {
res := make([]int, 1<<n)
for i := range res {
res[i] = i ^ i>>1 // reflected binary code
}
return res
}