Bird
Raised Fist0

Given the following Python code to generate Gray code sequence, what is the output of grayCode(2)?

easy🧾 Code Trace Q12 of Q15
Bit Manipulation - Gray Code
Given the following Python code to generate Gray code sequence, what is the output of grayCode(2)?
A[1, 0, 3, 2]
B[0, 1, 2, 3]
C[0, 1, 3, 2]
D[0, 2, 3, 1]
Step-by-Step Solution
Solution:
  1. Step 1: Compute values for i in range(4)

    For i=0: 0 ^ (0>>1)=0; i=1: 1 ^ (0)=1; i=2: 2 ^ (1)=2^1=3; i=3: 3 ^ (1)=3^1=2
  2. Step 2: Collect results in list

    The sequence is [0, 1, 3, 2], which matches the Gray code property.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Manual XOR calculation confirms the sequence [0,1,3,2] [OK]
Quick Trick: XOR with right-shifted index generates Gray code directly [OK]
Common Mistakes:
MISTAKES
  • Confusing the order of XOR and shift
  • Off-by-one errors in range leading to missing or extra elements
  • Misinterpreting the output as binary numbers instead of integers
Trap Explanation:
PITFALL
  • Candidates often confuse the bitwise operations or the range boundaries, leading to incorrect sequences.
Interviewer Note:
CONTEXT
  • Checks if candidate can mentally execute bitwise code and understand Gray code generation.
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