Gray Code

medium math backtracking bit manipulation

Problem

An n-bit Gray code sequence is a sequence of 2n integers where every value is in [0, 2n-1], the first integer is 0, every integer appears exactly once, and consecutive integers (including the wraparound from last to first) differ by exactly one bit. Return any valid n-bit Gray code sequence.

Inputn = 3
Output[0, 1, 3, 2, 6, 7, 5, 4]
Binary: 000, 001, 011, 010, 110, 111, 101, 100 — each adjacent pair differs in exactly one bit.

def gray_code(n):
    out = []
    for i in range(1 << n):
        out.append(i ^ (i >> 1))
    return out
function grayCode(n) {
  const out = [];
  for (let i = 0; i < (1 << n); i++) {
    out.push(i ^ (i >> 1));
  }
  return out;
}
class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> out = new ArrayList<>();
        for (int i = 0; i < (1 << n); i++) {
            out.add(i ^ (i >> 1));
        }
        return out;
    }
}
vector<int> grayCode(int n) {
    vector<int> out;
    for (int i = 0; i < (1 << n); i++) {
        out.push_back(i ^ (i >> 1));
    }
    return out;
}
Time: O(2n) Space: O(2n)