Bird
Raised Fist0

The following code attempts to find the single number in an array using XOR. Identify the line containing the subtle bug that causes incorrect results.

medium🐞 Bug Identification Q14 of Q15
Bit Manipulation - Single Number (XOR Self-Cancellation)
The following code attempts to find the single number in an array using XOR. Identify the line containing the subtle bug that causes incorrect results.
ALine 2: Initializing result to nums[0] instead of 0
BLine 4: Returning result without sorting
CLine 3: Looping over nums including the first element again
DLine 1: Function definition
Step-by-Step Solution
  1. Step 1: Analyze initialization of result

    Result initialized to nums[0], then XORed again with nums[0] in loop, cancelling it out incorrectly.
  2. Step 2: Understand correct initialization

    Result should start at 0 so XOR accumulates all elements exactly once.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Initializing to zero avoids double XOR of first element [OK]
Quick Trick: XOR accumulator must start at zero [OK]
Common Mistakes:
MISTAKES
  • Initializing with first element causes double XOR
  • Loop includes first element again
  • Misplaced return statement
Trap Explanation:
PITFALL
  • Starting with first element looks plausible but causes double cancellation of that element.
Interviewer Note:
CONTEXT
  • Checks if candidate spots subtle initialization bugs that break XOR logic.
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