InternDoor

The reflected Gray code

Mediumbit manipulation · recursion

Reported in interviews at (where)

A Gray code lists all 2^n numbers that fit in n bits, so that any two numbers next to each other in the list differ in exactly one bit.

The reflected Gray code is built this way. For 1 bit it is 0, 1. For n bits, take the list for n - 1 bits, then add that same list again in reverse order with the bit worth 2^(n-1) switched on in each of its numbers.

Return the reflected Gray code for n bits, as a list of numbers.

Example 1
Input
n = 1
Output
[0,1]

The starting list.

Example 2
Input
n = 2
Output
[0,1,3,2]

0, 1, then the reverse (1, 0) with 2 added: 3, 2. In binary: 00, 01, 11, 10.

Example 3
Input
n = 3
Output
[0,1,3,2,6,7,5,4]

The 2-bit list, then its reverse with 4 added to each number.

Limits

  • 1 <= n <= 16

Hints

Hint 1

Building the list by the rule, one bit at a time, takes O(2^n) and is fine.

Hint 2

There is also a formula: the i-th number of the reflected Gray code is i XOR (i >> 1).

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.