Bird
Raised Fist0

What is the output of the following Python function call generate_gray_code(1) given this implementation?

easy🧾 Trace Q3 of Q15
Bit Manipulation - Gray Code
What is the output of the following Python function call generate_gray_code(1) given this implementation?

def generate_gray_code(n):
    if n == 0:
        return [0]
    prev = generate_gray_code(n - 1)
    return prev + [x + (1 << (n - 1)) for x in reversed(prev)]
A[0, 1]
B[0, 1, 3, 2]
C[0, 1, 2, 3]
D[1, 0]
Step-by-Step Solution
Solution:
  1. Step 1: Base case for n=0

    The function returns [0].
  2. Step 2: For n=1

    prev = generate_gray_code(0) = [0]. Then return prev + [x + (1 << 0) for x in reversed(prev)] = [0] + [0 + 1] = [0, 1].
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sequence length is 2^1=2 and consecutive numbers differ by one bit. [OK]
Quick Trick: For n=1, Gray code is always [0,1] [OK]
Common Mistakes:
MISTAKES
  • Confusing the order of concatenation
  • Assuming the sequence length is 4 for n=1
  • Misinterpreting the bit shift operation
Trap Explanation:
PITFALL
  • Option B looks like Gray code for n=2 but question asks for n=1 output.
Interviewer Note:
CONTEXT
  • Tests understanding of recursive Gray code generation base and first step.
Master "Gray Code" in Bit Manipulation

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bit Manipulation Quizzes