Bird
Raised Fist0

What is the time complexity of generating an n-bit Gray code sequence using the optimal bitwise formula [i ^ (i >> 1) for i in range(1 ?

medium🪤 Complexity Trap Q13 of Q15
Bit Manipulation - Gray Code
What is the time complexity of generating an n-bit Gray code sequence using the optimal bitwise formula [i ^ (i >> 1) for i in range(1 << n)]?
AO(n)
BO((2^n)!)
CO(n * 2^n)
DO(2^n)
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the loop iteration count

    The list comprehension iterates over all integers from 0 to 2^n - 1, so 2^n iterations.
  2. Step 2: Analyze work per iteration

    Each iteration performs constant time bitwise operations (XOR and right shift), so O(1) per iteration.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Total time is proportional to 2^n, not multiplied by n or factorial [OK]
Quick Trick: Loop runs 2^n times with O(1) work each [OK]
Common Mistakes:
MISTAKES
  • Confusing n with 2^n and claiming O(n)
  • Assuming bitwise operations cost O(n)
  • Mistaking factorial complexity from brute force backtracking
Trap Explanation:
PITFALL
  • Option C looks plausible if candidate thinks bitwise ops cost O(n), and factorial complexity is a common confusion from brute force.
Interviewer Note:
CONTEXT
  • Tests if candidate understands exponential growth and constant-time bitwise operations.
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