Gray Code

Medium · Bit Manipulation · Math · Backtracking · Bit Manipulation

Problem

An n-bit Gray code is a sequence of 2^n integers such that:

Given n, return any valid n-bit Gray code sequence. Several sequences are valid for most n; any of them is accepted.

Examples

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

The only sequence is 0, 1.

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

00, 01, 11, 10: each step changes one bit, and 10 is one bit from 00. [0,2,3,1] is also accepted.

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

Every neighbor pair differs in one bit, and 4 (100) is one bit from 0. Other valid orders are also accepted.

Constraints

Approaches

Follow-up

To go back from a Gray code g to its position i, undo the XOR: i is the XOR of g >> k over all k, which can be computed by i = g; while g: g >>= 1; i ^= g. And a sequence that must start at some other value s is simply every code XORed with s.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…