Gray Code

Put all n-bit numbers in an order where each step changes exactly one bit.

An n-bit Gray code is an order of all the whole numbers from 0 to 2n - 1, each used once, in which every two neighbours differ in exactly one bit. The list starts at 0, and its last number must also differ from 0 in exactly one bit. Given n, between 1 and 16, return any such list.

Example 1
Input: n = 2
Output: [0, 1, 3, 2]
Explanation: in binary the list is 00, 01, 11, 10. Each step changes one bit, and so does the step from 10 back to 00.
Example 2
Input: n = 3
Output: [0, 1, 3, 2, 6, 7, 5, 4]
Solution

The Idea

Picture a volume knob that tells a chip its position as three bits, each read by its own small contact. Counting in plain binary, the step from 3 to 4 goes from 011 to 100, and all three bits change. The contacts never switch at exactly the same moment, so for an instant the chip may read 111 or 000, positions the knob never had.

A Gray code avoids that by putting the numbers in an order where each step changes a single bit. Bits are numbered from the right, starting at 0, so in the 2-bit code 10, bit 1 is 1 and bit 0 is 0. Example 1 is a Gray code for two bits: 00, 01, 11, 10. The steps change bit 0, then bit 1, then bit 0 again, and the step from 10 back to 00 changes bit 1.

Two bits can be ordered by hand. Example 2 already needs all eight 3-bit numbers, and with n = 16 there are 65,536 of them. How can we build the list for any n?

By reusing the list for one bit fewer. Look at the picture below.

The 3-bit Gray code built by reflecting. On the left, the 2-bit code with a 0 in front: 000, 001, 011, 010. After a mirror line, the same list reversed with bit 2 set to 1: 110, 111, 101, 100. Across the mirror, 010 to 110, and back from 100 to 000, only bit 2 changes.

The blue half, labelled "the 2-bit code, with a 0 in front", is Example 1 with a 0 written as bit 2. Each step inside it changes one bit, as before. The teal half, labelled "the same list reversed, bit 2 set to 1", holds 10, 11, 01, 00 in that order, each with an orange 1 in front. Walking a list backwards still changes one bit per step, and the orange 1 never changes, so the teal half is fine too.

That leaves the two places where the halves meet, drawn as orange lines. Across the dashed line labelled mirror, the line marked "010 to 110: only bit 2 changes" joins the last code of the blue half to the first code of the teal half. Both end in 10, so bit 2 is the one difference. The line marked "back from 100 to 000" works the same way, because both end in 00.

Read as numbers, the row is 0, 1, 3, 2, 6, 7, 5, 4, the answer of Example 2. So each extra bit doubles the list: copy it, reverse the copy, and set the new bit in every number of the copy. Because of this mirroring, the order is called the reflected binary Gray code, and it is the order both examples show.

Solution Approach

Two direct ways lead from the mirror picture to code: repeat the mirror step in a loop, or compute each code from its place in the list with a formula. A third option searches one bit flip at a time, and it breaks down for large n. The Java solution uses the formula.

Repeating the mirror step

How would the picture work as a loop? Start with the list [0]. For bit 0, walk the list backwards and add each value with bit 0 set, which gives [0, 1]. For bit 1, the same walk adds 3 and 2, giving [0, 1, 3, 2]. For bit 2 it adds 6, 7, 5 and 4.

Setting a bit takes two Java operators. The left shift 1 << 2 moves the single 1 of the number 1 two places left, to 100, which is 4. OR, written |, gives a 1 wherever either number has one, so 2 | 4 turns 010 into 110, which is 6.

The loop has to read back the list it is building, though. Could we get the code at a given place without the codes before it?

A formula for each code

Write Example 2 again as a table. Each code's place in the list, numbered 0 to 7, is called i. Next to i in binary come the same bits moved one place to the right, then the code itself.

place ii in binary (bits 2 1 0)i shifted right by onecode in binarycode as a number
00000000000
10010000011
20100010113
30110010102
41000101106
51010101117
61100111015
71110111004

Look at the row for place 3. In 011, bits 0 and 1 are both 1, so they match, and bit 0 of the code is 0. Bits 1 and 2 are 1 and 0, which differ, so bit 1 of the code is 1. Bit 2 is 0, and so is bit 3, since 011 has no fourth digit, so bit 2 of the code is 0. That gives 010, the code at place 3.

Each bit of the code is 1 exactly where a bit of i differs from the bit to its left. Java compares all those pairs at once with two operators. The right shift i >> 1 moves every bit one place right, so the bit to the left of each position lands on that position: the column "i shifted right by one". XOR, written ^, puts a 1 where two numbers' bits differ and a 0 where they match. So the code at place i is i ^ (i >> 1).

Why does each step change only one bit of the code? Going from place 3 to place 4, 011 becomes 100: the run of 1s at the right end turns into 0s, and the 0 just above it turns into 1. Inside the run, the neighbouring bits match before and after, so those code bits stay 0. Bits 1 and 2 differ both before and after, so bit 1 of the code stays 1. Only bit 2 of the code changes, from 010 to 110, because the new 1 now differs from the 0 above it. Every other step works the same way: the one code bit that changes is where the new 1 meets the bit above it.

The last place is all 1s, 111, and its code is 100, a single 1 at the top. That is one bit away from 0, so the wrap-around holds for any n. For every n from 1 to 16, our runs of the formula and of the mirror loop gave the same lists.

Searching one bit flip at a time

What if the formula did not come to mind? A search can build the list from 0. Each time it tries the n numbers one bit flip away from the last value, lowest bit first, and takes the first one not used yet. If every such number is already used before the list is full, it removes the last value and tries the next flip from the value before it; undoing a choice like this is called backtracking.

For every n from 1 to 12, our runs never had to take a value back, and they returned the same list as the formula. The search calls itself once for every value it places, though, so it nests 2n calls deep. For n = 13 to 16 our runs stopped with StackOverflowError on the default thread stack, so the formula is the better choice.

Java Solution

The method grayCode works in these steps:

  1. First, compute total = 1 << n, the number of codes, 2n. With n at most 16, that is at most 65,536, far inside a 32-bit Java int.
  2. Create the list codes with room for total values.
  3. Loop with i over the places 0 to total - 1, and add i ^ (i >> 1) to codes for each one.
  4. After the loop, return codes.

The main method runs both examples and n = 1. Two helpers check the results: inBinary writes each code as n binary digits, and isGrayCode checks that every number appears once and every step, the wrap-around too, flips one bit. The main method runs that check on n = 16 and on plain counting, [0, 1, 2, 3].

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class GrayCode {

    public static List<Integer> grayCode(int n) {
        int total = 1 << n;                    // 2^n codes
        List<Integer> codes = new ArrayList<>(total);
        for (int i = 0; i < total; i++) {
            codes.add(i ^ (i >> 1));           // 1 where neighbouring bits of i differ
        }
        return codes;
    }

    // Writes each code as n binary digits, so 3 with n = 3 becomes 011
    static List<String> inBinary(List<Integer> codes, int n) {
        List<String> out = new ArrayList<>();
        for (int code : codes) {
            String bits = Integer.toBinaryString(code);
            out.add("0".repeat(n - bits.length()) + bits);
        }
        return out;
    }

    // True if every value 0..2^n - 1 appears once and each step, wrap-around too, flips one bit
    static boolean isGrayCode(List<Integer> codes, int n) {
        Set<Integer> seen = new HashSet<>(codes);
        if (codes.size() != (1 << n) || seen.size() != codes.size() || codes.get(0) != 0) {
            return false;
        }
        for (int k = 0; k < codes.size(); k++) {
            int next = codes.get((k + 1) % codes.size());
            if (next >= (1 << n) || Integer.bitCount(codes.get(k) ^ next) != 1) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(grayCode(2));
        System.out.println(grayCode(3));
        System.out.println(inBinary(grayCode(3), 3));
        System.out.println(grayCode(1));
        List<Integer> big = grayCode(16);
        System.out.println("n = 16: " + big.size() + " codes, last " + big.get(big.size() - 1)
                + ", valid: " + isGrayCode(big, 16));
        List<Integer> counting = List.of(0, 1, 2, 3);
        System.out.println("plain counting " + counting + " valid: " + isGrayCode(counting, 2));
    }
}

Running it prints:

Output
[0, 1, 3, 2]
[0, 1, 3, 2, 6, 7, 5, 4]
[000, 001, 011, 010, 110, 111, 101, 100]
[0, 1]
n = 16: 65536 codes, last 32768, valid: true
plain counting [0, 1, 2, 3] valid: false

The first two lines, [0, 1, 3, 2] and [0, 1, 3, 2, 6, 7, 5, 4], match Examples 1 and 2. The third line writes the second list in binary, [000, 001, 011, 010, 110, 111, 101, 100], the same row as the picture, and each step changes one digit. For n = 1 the list is [0, 1].

Look at the line for n = 16. It has 65536 codes, and the last one is 32768, a 1 followed by fifteen 0s in binary, one bit away from 0. The check prints valid: true for the whole list. In the last line, plain counting fails the same check: the step from 1 to 2, 01 to 10, changes two bits.

Complexity

The method does the same small amount of work for every code it outputs.

  • Time: O(2n), because the loop runs once for each of the 2n places, and each code costs one shift and one XOR.
  • Space: O(1) besides the output, because apart from the list of 2n codes, which is the answer, the method keeps only i and total.