Gray Code
Put all n-bit numbers in an order where each step changes exactly one bit.
An nn
Example 1
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
Output: [0, 1, 3, 2, 6, 7, 5, 4]
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 nn
By reusing the list for one bit fewer. Look at the picture below.
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
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|2 | 4
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 ii
| place i | i in binary (bits 2 1 0) | i shifted right by one | code in binary | code as a number |
|---|---|---|---|---|
| 0 | 000 | 000 | 000 | 0 |
| 1 | 001 | 000 | 001 | 1 |
| 2 | 010 | 001 | 011 | 3 |
| 3 | 011 | 001 | 010 | 2 |
| 4 | 100 | 010 | 110 | 6 |
| 5 | 101 | 010 | 111 | 7 |
| 6 | 110 | 011 | 101 | 5 |
| 7 | 111 | 011 | 100 | 4 |
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 ii >> 1^ii ^ (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 nn
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
For every nnStackOverflowError
Java Solution
The method grayCode
- First, compute
, the number of codes, 2n. Withtotal = 1 << n at most 16, that is at most 65,536, far inside a 32-bit Javan .int - Create the list
with room forcodes values.total - Loop with
over the places 0 toi - 1, and addtotal toi ^ (i >> 1) for each one.codes - After the loop, return
.codes
The mainninBinarynisGrayCodemainn[0, 1, 2, 3]
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:
[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][0, 1, 3, 2, 6, 7, 5, 4][000, 001, 011, 010, 110, 111, 101, 100]n[0, 1]
Look at the line for nvalid: true
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
andi .total