oneby7

Recursion and Backtracking Generating every choice

329. Gray Code

Medium

Given an integer n, return an n-bit Gray code. That is a list of all 2n integers from 0 to 2n − 1, each exactly once, where each number differs from the one before it in exactly one bit. The list starts at 0, and its last number must also differ from 0 in exactly one bit, so the list closes into a loop.

Two numbers differ in exactly one bit when their binary forms match in every digit but one. 5 (101) and 7 (111) differ in one bit. 5 and 6 (110) differ in two.

Many lists follow these rules, and any of them is a correct answer. The result shows a valid Gray code when your list is one. Otherwise it names the first thing wrong, such as values 5 and 6 differ in 2 bits, 6 appears twice or the sequence starts at 1, not 0.

Example 1

Input: n = 3

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

Explanation: In binary the list is 000, 001, 011, 010, 110, 111, 101, 100. Each step changes one digit, and the last number, 100, differs from 000 in one digit too. [0,2,6,4,5,7,3,1] is also correct.

Example 2

Input: n = 1

Output: [0,1]

Explanation: The only numbers are 0 and 1. They differ in one bit, so the step from 0 to 1 and the step from 1 back to 0 are both fine.

Example 3

Input: n = 2

Output: [0,1,3,2]

Explanation: In binary that is 00, 01, 11, 10. Counting up, [0,1,2,3], is wrong: 1 (01) and 2 (10) differ in two bits.

Check your understanding

Work out the answer for this input before you write any code.

n = 3

Constraints

  • 1 ≤ n ≤ 20

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.