Skip to content
Decoder

Gray Code

Medium

Problem

An n-bit Gray code is an ordering of all the numbers from 0 to 2^n - 1 where:

- it starts at 0, - every number appears exactly once, - any two neighbours differ in exactly one bit, and so do the last and the first.

Write gray_code(n) (Python) / grayCode(n) (TypeScript) that returns any valid n-bit Gray code as a list of integers. Many answers are valid; the tests check the rules, not one specific list.

Example 1

Input
n = 2
Output
[0, 1, 3, 2]
Why
00, 01, 11, 10

Example 2

Input
n = 1
Output
[0, 1]

Constraints

  • 1 <= n <= 16

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.