The problem is to generate a sequence called Gray Code for a given number of bits n
. Gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n
representing the total number of bits in the code, we need to return any sequence of Gray code.
Input: n = 2
Output: [0, 1, 3, 2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
Given n
= 2, [0, 1, 3, 2]
is a valid Gray code sequence. Another valid sequence is [0, 2, 3, 1]
.
n = 0
?
n = 0
, the Gray code sequence would be [0]
.Once these clarifications are made, we can proceed with solving the problem.
[0]
for n = 0
.n
, build the new sequence based on the existing sequence.1 << (current level - 1)
).Here’s the implementation of the above strategy in Python:
def grayCode(n):
# Base case for zero bits
result = [0]
for i in range(n):
# Reflect the current sequence
reflected = [x | (1 << i) for x in reversed(result)]
# Extend the original sequence with the reflected sequence
result.extend(reflected)
return result
[0]
for n = 0
.[0]
[0]
-> Reflect -> [0]
-> Append 1 << 0
to the reflected part -> [1]
[0, 1]
[0, 1]
[1, 0]
-> Append 1 << 1
-> New values: [3, 2]
[0, 1, 3, 2]
This process continues until all levels are processed.
The algorithm has a time complexity of O(2^n):
2^i
, where i
is the current bit level.Thus, combining these facts, the overall time complexity is O(2^n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?