Gray Code

An n-bit Gray code sequence is a list of 2^n integers where every integer is in [0, 2^n - 1], the first integer is 0, each integer appears once, adjacent integers differ in exactly one bit, and the first and last integers also differ in exactly one bit. Given n, return any valid n-bit Gray code sequence.

30:00

Gray Code
medium
Free written solution
Topics
Companies

An n-bit Gray code sequence is a list of 2^n integers where every integer is in [0, 2^n - 1], the first integer is 0, each integer appears once, adjacent integers differ in exactly one bit, and the first and last integers also differ in exactly one bit. Given n, return any valid n-bit Gray code sequence.

Example 1:
Input: {"n":2}
Output: [0,1,3,2]
Constraints:
  • 1≤n≤161 \leq n \leq 16

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":2}

We need all 4 2-bit codes in an order where neighbours (and the last and first) differ in exactly one bit.

Each code is i XOR (i >> 1)

i
·
·
i >> 1
·
·
XOR
·
·

Bit k of the code is 1 exactly when bits k and k+1 of i differ. Counting up by one changes i's lowest run of bits, which changes only one such neighbour pair.

All codes in value order; the path is the Gray sequence

0 / 4

00011011

result

[ ]

Variables
VariableValue
n2
size4
DepthFunction Call
Stack empty
0/9