Bird
Raised Fist0

In the following code snippet for finding two unique numbers, which line contains the subtle bug causing incorrect results?

medium🐛 Buggy Code Q7 of Q15
Bit Manipulation - Single Number III (Two Singles)
In the following code snippet for finding two unique numbers, which line contains the subtle bug causing incorrect results? ```python def findTwoSingles(nums): xor_all = 0 for num in nums: xor_all ^= num set_bit = xor_all & (xor_all - 1) # Bug here num1 = 0 num2 = 0 for num in nums: if num & set_bit: num1 ^= num else: num2 ^= num return [num1, num2] ```
ALine with 'if num & set_bit:' inside the second loop
BLine with 'xor_all ^= num' inside the loop
CLine with 'set_bit = xor_all & (xor_all - 1)'
DLine with 'return [num1, num2]'
Step-by-Step Solution
Solution:
  1. Step 1: Identify purpose of set_bit

    It should isolate the rightmost set bit of xor_all.
  2. Step 2: Check the expression

    Correct expression is xor_all & (-xor_all) or xor_all & ~(xor_all - 1), not xor_all & (xor_all - 1).
  3. Step 3: Understand impact

    Using xor_all & (xor_all - 1) clears the rightmost set bit, resulting in zero or wrong mask.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Correct mask isolates rightmost set bit [OK]
Quick Trick: Use xor_all & (-xor_all) to get rightmost set bit [OK]
Common Mistakes:
MISTAKES
  • Using xor_all & (xor_all - 1) clears the bit instead of isolating it
  • Misunderstanding bitwise negation
  • Incorrect partitioning due to wrong mask
Trap Explanation:
PITFALL
  • The wrong bitwise operation looks similar but changes the mask meaning.
Interviewer Note:
CONTEXT
  • Tests knowledge of bitwise operations and debugging skills.
Master "Single Number III (Two Singles)" 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