Back to course home
0% completed
Vote For New Content
Gray Code (medium)
Problem Statement
Given a positive integer n
, return any valid n-bit
gray code sequence
.
An n-bit
gray code sequence
is a sequence containing integers where:
- Each integer is in the inclusive range [0, 2<sup>n</sup> - 1].
- Sequence always starts with 0.
- All integers are unique in the sequence.
- The
binary representation
ofevery pair
ofadjacent integers
differs
byexactly one bit
. - The
binary representation
of thefirst
andlast
integersdiffers
byexactly one bit
.
Examples
-
Example 1
- Input:
n = 4
- Expected Output:
[0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8]
- Justification: This sequence starts at 0 and each subsequent number differs from the previous one by exactly one bit. The sequence covers all numbers from 0 to 15 (which is 2^4 - 1), adhering to the Gray Code property. It also ensures that the first and last numbers (0 and 8) differ by only one bit.
- Input:
-
Example 2
- Input:
n = 1
- Expected Output:
[0, 1]
- Justification: With a single bit, the sequence can only be [0, 1], as both numbers differ by exactly one bit, and the sequence starts with 0.
- Input:
-
Example 3
- Input:
n = 3
- Expected Output:
[0, 1, 3, 2, 6, 7, 5, 4]
- Justification: This sequence for 3 bits starts at 0, and each subsequent number differs from the previous by exactly one bit. Additionally, the first and last numbers (0 and 4) differ by only one bit, satisfying all the conditions of Gray Code.
- Input:
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Like the course? Get enrolled and start learning!
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible