Skip to content

Gray Code

MediumBacktracking
Decode it first. Clues, constraints, pattern and plan before any code.

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.

n = 2  →  [0, 1, 3, 2]     (00, 01, 11, 10)
n = 1  →  [0, 1]

Constraints

  • 1 <= n <= 16