A Gray code of size n is an ordering of all 2^n numbers from 0 to 2^n − 1, starting at 0, where each number differs from the next in exactly one bit of its binary form. The last number must also differ from the first in exactly one bit, so the sequence closes into a loop.
Given n, return any Gray code of size n as a list of integers. Many orderings work; any valid one is accepted.
Example 1
Input: n = 3 Output: [0, 1, 3, 2, 6, 7, 5, 4] Why: 000 001 011 010 110 111 101 100, one bit at a time; 100 to 000 closes it
1 more example and the constraints
Example 2
Input: n = 4 Output: [0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8] Why: the n = 3 list, then its mirror with bit 3 set
Constraints
- 1 ≤ n ≤ 16
- The list has exactly 2^n numbers, each used once
- The first number is 0
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Flip the lowest new bitO(n · 2^n)
- Mirror and prefixO(2^n)
- XOR with the halfO(2^n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 16 | Verdict |
|---|---|---|---|
| Flip the lowest new bit | O(n · 2^n) | Works; extra memory | |
| Mirror and prefix | O(2^n) | Easy to derive and prove | |
| XOR with the half | O(2^n) | Best; one line |
n = number of bits; the output always has 2^n numbers.
Edge cases to test
- n = 1. The answer is [0, 1]: two numbers, one bit apart in both directions.
- The wrap-around. The last number must also be one bit away from 0, not only its neighbour before it.
- n = 16. 65,536 numbers. The output itself is the cost, so the work per number must be O(1) or O(n).
- Many valid answers. [0, 2, 3, 1] is as correct as [0, 1, 3, 2] for n = 2; check the rules, not one fixed list.
Common mistakes
- Mirroring without setting the new bit, which repeats numbers instead of adding new ones.
- Writing
i ^ (i << 1)ori >> 1alone instead ofi ^ (i >> 1). - Forgetting that the last number must be one bit away from the first.
How to talk through it
- 1Clarify. Any valid order accepted? Must the sequence start at 0 and close into a loop?
- 2Start with a search. Numbers are cube corners; walk from 0 flipping the lowest bit that reaches a new number.
- 3Show the mirror. A b-bit answer plus its reversed copy with bit b set is a (b + 1)-bit answer.
- 4Give the formula.
i ^ (i >> 1): from i to i + 1, the XOR leaves exactly one bit changed. - 5Test out loud. Write n = 3 in binary and check every neighbour, including 4 back to 0.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?