Gray codes: a cyclic list of all bit strings with one change at a time
Statement
Let . Show that the binary strings of length can be arranged in a cyclic list such that any two consecutive strings (including and ) differ in exactly one position.
Hint
Build the list for from the list for : write it forward with a in front, then backward with a in front.
Show solutionHide solution
Solution
Construction. For : works.
Suppose () is a valid cyclic list for length . Define for length the list
It contains every string once. The first half contains all strings starting with , the second half all those starting with , each once.
Consecutive strings differ in one position.
- Inside the first half, and differ exactly where do.
- Inside the second half, same argument.
- At the middle, and differ only in the first position.
- Closing the cycle, and differ only in the first position.
By induction the list exists for every .
Explicit form. The -th string () can be taken to be the binary expansion of . Consecutive strings differ in one bit; and gives , which differs from the string for in one bit.
Remark. This is a Hamiltonian cycle in the -dimensional cube graph. Gray codes are used in rotary encoders.
Lesson. "Reflect and prefix" constructions work for recursive structures; check the seams.