List every n-bit number so each differs from the next by exactly one bit. Start with 0, then for each new bit mirror the list and switch that bit on in the mirrored half; the seam changes only the new bit. Same as i XOR (i >> 1).
▼The problem
LeetCode 89 (Medium). Given n, return any valid n-bit Gray code sequence: 2ⁿ distinct numbers in [0, 2ⁿ), starting at 0, where every pair of neighbours, and the last and first numbers, differ in exactly one bit.
Examples: n = 2 → [0,1,3,2] (00, 01, 11, 10; the example scene); n = 1 → [0,1] (checked, not shown).
The solution
def grayCode(n):
res = [0]
for i in range(n):
bit = 1 << i
res += [x + bit for x in reversed(res)]
return res
def grayCode(n): # closed form
return [i ^ (i >> 1) for i in range(1 << n)]Transcript
Gray Code. Given n, list all two to the n numbers with n bits, starting at zero, so each one differs from the next in exactly one bit, even the last one back to the first.
Think of each bit as a signal flag: raised is one, lowered is zero. Each step may move just one flag. Take n equals two. Zero zero, zero one, one one, one zero. That's zero, one, three, two, and one flag drops to wrap back to zero.
Why not just count? One to two flips two bits, and three to four moves all three flags. Counting breaks the rule.
A search works. From zero, move any flag to reach an unused number, and back up when you get stuck. But dead ends pile up, and it can take exponential time.
Here's the trick: reflect and prefix. Take a valid list and write it again below, in reverse, like a reflection in still water. Then raise one new flag on every reflected number. Each half still moves one flag per step. At the seam, the two numbers are mirror twins, so only the new flag differs. The two ends are twins too, so the wrap works.
Let's build three bits. Start with zero. Reflect, and raise flag one: zero, one. Reflect again, raise flag two: three, two. Once more, raise flag four: six, seven, five, four. Eight numbers, each one flag from the next, even four back to zero.
In code, start with a list holding zero. For each bit, extend the list with its reverse, adding that bit to each number. Or use the closed form: number i is i XOR i shifted right by one. Five shifted is two, five XOR two is seven, and seven sits at position five. A match.
We make two to the n numbers with constant work each, so the time is O of two to the n, the size of the answer. Extra space is constant.
Reflect the list, raise the new flag, repeat. That's Gray Code.