Gray Code

An n-bit gray code sequence is a sequence of 2^n integers where:

  • Every integer is in the inclusive range [0, 2^n - 1].
  • The first integer is 0.
  • An integer appears no more than once in the sequence.
  • The binary representation of every pair of adjacent integers differs by exactly one bit.
  • The binary representation of the first and last integers differs by exactly one bit.

Given an integer n, return any valid n-bit gray code sequence.

Example 1
Inputn = 2
Output[0,1,3,2]
The sequence is valid because adjacent binary values differ by exactly one bit, and the last value 10 also differs from the first value 00 by exactly one bit.
Example 2
Inputn = 1
Output[0,1]
The sequence starts with 0 and the two 1-bit values differ by exactly one bit, including between the last and first values.

Constraints

  • 1 <= n <= 16

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate