Bird
Raised Fist0

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

medium📊 Complexity Q5 of Q15
Bit Manipulation - Gray Code
What is the time complexity of generating an n-bit Gray code sequence using the list comprehension [i ^ (i >> 1) for i in range(1 << n)]?
AO(n * 2^n)
BO(2^n)
CO(n^2)
DO(n)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the range

    The range is from 0 to 2^n - 1, so 2^n iterations.
  2. Step 2: Operation per iteration

    Each iteration computes i ^ (i >> 1), which is O(1) bitwise operations.
  3. Step 3: Total complexity

    Total time is number of iterations times O(1) = O(2^n).
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Each element computed independently in constant time. [OK]
Quick Trick: Bitwise XOR per element is constant time, total 2^n elements [OK]
Common Mistakes:
MISTAKES
  • Assuming bitwise operations take O(n) time
  • Confusing with recursive approach complexity
  • Ignoring the size of the output sequence
Trap Explanation:
PITFALL
  • Option A confuses bitwise operation cost with number of bits n.
Interviewer Note:
CONTEXT
  • Tests knowledge of time complexity for bitwise 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