SDE & MLE Prep

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)]