Bird
Raised Fist0

Identify the subtle bug in the following XOR-based single number code snippet: def singleNumber(nums): result = nums[0] for num in nums: result ^= num return result

medium🐞 Bug Identification Q7 of Q15
Bit Manipulation - Single Number (XOR Self-Cancellation)
Identify the subtle bug in the following XOR-based single number code snippet: def singleNumber(nums): result = nums[0] for num in nums: result ^= num return result
AInitializing result with nums[0] causes double XOR of first element
BLoop should start from index 1 instead of 0
CXOR operation is incorrect, should use addition
DNo bug, code works correctly
Step-by-Step Solution
Solution:
  1. Step 1: Analyze initialization

    result starts as nums[0], then XORed again in loop starting at nums[0].
  2. Step 2: Effect of double XOR

    First element XORed twice cancels out, losing that element's contribution.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Double XOR of first element causes wrong result [OK]
Quick Trick: Initialize result to 0, not first element [OK]
Common Mistakes:
MISTAKES
  • Starting loop at 0 with non-zero init
  • Using addition instead of XOR
Trap Explanation:
PITFALL
  • Candidates often initialize with first element but still XOR it again, causing cancellation.
Interviewer Note:
CONTEXT
  • Tests bug spotting in subtle initialization errors.
Master "Single Number (XOR Self-Cancellation)" 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