sagelearnai

Gray Code

Difficulty: Medium · Pattern: Bit Manipulation · LeetCode #89

Return any n-bit Gray code sequence: 2ⁿ distinct integers in [0, 2ⁿ), starting at 0, where consecutive values (including the last and the first) differ in exactly one bit. The tests validate your sequence.

Examples

text
n = 2  →  [0,1,3,2]     (00, 01, 11, 10)
n = 1  →  [0,1]

Hints

  1. Reflection: take the (n−1)-bit sequence, append its reverse with the top bit set.
  2. Or the closed form: the i-th Gray code is i ^ (i >> 1).

Approach

Binary-reflected Gray code: g(i) = i ^ (i >> 1) for i in 0..2ⁿ−1.

Why do neighbors differ in one bit? Going from i to i+1 flips a suffix 0111…1 → 1000…0. After XORing each number with itself shifted right, only one bit of the result changes: the position of that flipped-suffix's leading bit. The sequence also wraps cyclically, since g(2ⁿ−1) = 100…0.

Uses: rotary encoders and Karnaugh maps, wherever a transition between neighboring states must change only one signal.

Complexity

Time: O(2ⁿ). Space: O(2ⁿ) for the output.

Python solution
def grayCode(n):
    return [i ^ (i >> 1) for i in range(1 << n)]
JavaScript solution
function grayCode(n) {
  let res = [0];
  for (let b = 0; b < n; b++) {
    const top = 1 << b;
    res = res.concat([...res].reverse().map((x) => x | top));
  }
  return res;
}