Bird
Raised Fist0

The following Python code counts set bits for all numbers from 0 to n by converting each number to a binary string and counting '1's. What is the main inefficiency in this approach?

medium🔍🐞 Bug Finding Q7 of Q15
Bit Manipulation - Counting Bits (0 to N)
The following Python code counts set bits for all numbers from 0 to n by converting each number to a binary string and counting '1's. What is the main inefficiency in this approach?
def countBits(n):
    res = []
    for i in range(n+1):
        res.append(bin(i).count('1'))
    return res
ACounting '1's in string is incorrect for negative numbers
BConverting each number to binary string repeatedly causes high overhead
CThe loop should start from 1, not 0
DThe function does not handle large n due to recursion depth
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the code

    Each number i is converted to a binary string using bin(i), then '1's are counted.
  2. Step 2: Identify inefficiency

    Converting integers to strings repeatedly is costly in time and memory compared to bitwise operations.
  3. Step 3: Consider alternatives

    Bit manipulation or dynamic programming approaches avoid string conversion and are more efficient.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    String conversion inside loop is expensive [OK]
Quick Trick: Avoid string conversions inside loops for bit counting [OK]
Common Mistakes:
MISTAKES
  • Thinking counting '1's in string is incorrect for positive numbers
  • Assuming loop start index affects correctness
  • Confusing recursion with iteration in this code
Trap Explanation:
PITFALL
  • String conversion is correct but inefficient, distracts from performance issue
Interviewer Note:
CONTEXT
  • Tests ability to identify inefficiencies in naive bit counting implementations
Master "Counting Bits (0 to N)" 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