Bird
Raised Fist0

Consider the following buggy Python code intended to generate Gray code sequence. Which line contains the subtle bug that breaks the Gray code property?

medium🐞 Bug Identification Q14 of Q15
Bit Manipulation - Gray Code
Consider the following buggy Python code intended to generate Gray code sequence. Which line contains the subtle bug that breaks the Gray code property?
ALine 2: Using XOR with (i << 1) instead of (i >> 1)
BLine 3: Incorrect range boundary in range(1 << n)
CLine 1: Missing base case for n=0
DLine 5: Printing the result instead of returning
Step-by-Step Solution
Solution:
  1. Step 1: Identify the bitwise operation used

    The code uses i ^ (i << 1) instead of the correct i ^ (i >> 1).
  2. Step 2: Understand impact on Gray code property

    Left shifting i doubles the value, causing incorrect bit patterns and breaking the one-bit difference property between consecutive numbers.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct Gray code uses right shift, not left shift [OK]
Quick Trick: XOR with right shift generates Gray code; left shift breaks it [OK]
Common Mistakes:
MISTAKES
  • Confusing left and right bit shifts in XOR formula
  • Ignoring base case n=0 which is trivial but not critical here
  • Misunderstanding range boundaries or print vs return
Trap Explanation:
PITFALL
  • The left shift looks similar but changes the sequence drastically; other lines look plausible but are correct.
Interviewer Note:
CONTEXT
  • Checks if candidate understands the exact bitwise formula and its correctness conditions.
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