Maths WorkshopMaths problems with full solutions
Exercise 1250Combinatorics › Counting principlesOlympiadAdded 4 Nov 2026

Gray codes: a cyclic list of all bit strings with one change at a time

#Gray code#induction#hypercube#constructions

Statement

Let n≥2n\ge2. Show that the 2n2^n binary strings of length nn can be arranged in a cyclic list g1,g2,…,g2ng_1,g_2,\dots,g_{2^n} such that any two consecutive strings (including g2ng_{2^n} and g1g_1) differ in exactly one position.

Hint

Build the list for nn from the list for n−1n-1: write it forward with a 00 in front, then backward with a 11 in front.

Show solutionHide solution

Solution

Construction. For n=2n=2: 00,01,11,1000,01,11,10 works.

Suppose g1,…,gmg_1,\dots,g_m (m=2n−1m=2^{n-1}) is a valid cyclic list for length n−1n-1. Define for length nn the list
0g1, 0g2, …, 0gm, 1gm, 1gm−1, …, 1g1.0g_1,\,0g_2,\,\dots,\,0g_m,\,1g_m,\,1g_{m-1},\,\dots,\,1g_1.

It contains every string once. The first half contains all strings starting with 00, the second half all those starting with 11, each once.

Consecutive strings differ in one position.
- Inside the first half, 0gi0g_i and 0gi+10g_{i+1} differ exactly where gi,gi+1g_i,g_{i+1} do.
- Inside the second half, same argument.
- At the middle, 0gm0g_m and 1gm1g_m differ only in the first position.
- Closing the cycle, 1g11g_1 and 0g10g_1 differ only in the first position.

By induction the list exists for every n≥2n\ge2.

Explicit form. The kk-th string (k=0,…,2n−1k=0,\dots,2^n-1) can be taken to be the binary expansion of k⊕⌊k/2⌋k\oplus\lfloor k/2\rfloor. Consecutive strings differ in one bit; and k=2n−1k=2^n-1 gives 10⋯010\cdots0, which differs from the string 00 for k=0k=0 in one bit.

Remark. This is a Hamiltonian cycle in the nn-dimensional cube graph. Gray codes are used in rotary encoders.

Lesson. "Reflect and prefix" constructions work for recursive structures; check the seams.