Gray Code (LeetCode 89): Solution and Explanation

Medium
Math
Backtracking
Bit Manipulation

List all 2^n integers of n bits, starting at 0, so that every two neighbours differ in exactly one bit, including the last and the first.

Intuition

Plain counting fails: going from 01 to 10 changes two bits. We need an order where every step flips exactly one bit, which is a walk around the corners of an n-dimensional cube that visits each corner once and returns home.

The reflected construction gives such a walk. Take the sequence for n - 1 bits, then append the same sequence in reverse with the new top bit set. Inside each half only one bit changes per step, at the seam only the top bit changes, and the last code (top bit plus 0) is one bit from 0.

Unrolling that recursion gives a closed form: code(i) = i XOR (i >> 1). Bit k of the code says whether bits k and k+1 of i differ. Adding 1 to i flips a run of trailing bits, which changes exactly one of those neighbour pairs, so exactly one code bit changes.

Approach: Closed-form reflected Gray code

  1. Create an empty result list.
  2. For every i from 0 to 2^n - 1, append i ^ (i >> 1).
  3. Return the list. It starts at 0, covers every n-bit value once, and each neighbour pair (and the wrap) differs in one bit.

Step-by-step example

n = 2
  1. i = 0 = 00: 00 XOR 00 = 00, append 0.
  2. i = 1 = 01: 01 XOR 00 = 01, append 1. One bit changed from 00.
  3. i = 2 = 10: 10 XOR 01 = 11, append 3. Only the high bit changed.
  4. i = 3 = 11: 11 XOR 01 = 10, append 2. Only the low bit changed, and 10 is one bit away from 00.
  5. Result: [0,1,3,2].

Code: Python, Java, C++

1class Solution:
2    def grayCode(self, n: int) -> List[int]:
3        result = []
4        for i in range(1 << n):
5            result.append(i ^ (i >> 1))
6        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(2^n)

One constant-time XOR and shift per output value, and there are 2^n values.

Space

O(1)

Apart from the 2^n integers we must return, only the loop counter is stored.

Other approaches

Reflect and prefix (time O(2^n), space O(1) extra)

Start with [0]. For each bit k from 0 to n - 1, walk the current list backwards and append each value with bit k set. Produces the same sequence without the formula.

Backtracking over bit flips (time O(n 2^n), space O(2^n))

From the current code, try flipping each bit and recurse on unvisited codes until all 2^n are used. Works and generalises to other constraints, but is slower and more code.

Common mistakes

  • Listing 0..2^n - 1 in plain binary order. Steps like 011 to 100 flip three bits.
  • Forgetting the wrap-around rule. The last value must also be one bit away from 0; the reflected sequence ends at 2^(n-1), which satisfies it.
  • Writing (1 << n) without parentheses in a loop condition like i < 1 << n in languages where precedence surprises you. Bracket the shift.

Frequently asked questions

Is [0,1,3,2] the only answer for n = 2?

No. [0,2,3,1] is also valid, and larger n has many more valid orders. The judge checks the rules, so any valid sequence passes.

Why does i XOR (i >> 1) change exactly one bit per step?

Code bit k is 1 when bits k and k+1 of i differ. Incrementing i turns a trailing block 0111..1 into 1000..0. Inside that block, neighbouring bits stay equal to each other, so only the pair at the top edge of the block changes.

How do I get back from a Gray code to i?

XOR together all right shifts of the code: i = g ^ (g >> 1) ^ (g >> 2) ^ ... Each bit of i is the parity of the code bits at or above it.