Bird
Raised Fist0

In the following Python code to find the missing number using XOR, which line causes incorrect results when the missing number is n?

medium🔍🐞 Bug Finding Q7 of Q15
Bit Manipulation - Find the Missing Number
In the following Python code to find the missing number using XOR, which line causes incorrect results when the missing number is n?
def find_missing(nums):
    n = len(nums)
    xor_val = 0
    for i in range(n):
        xor_val ^= nums[i]
    for i in range(n):
        xor_val ^= i
    return xor_val
ALine 6: for i in range(n): xor_val ^= i
BLine 4: for i in range(n): xor_val ^= nums[i]
CLine 3: xor_val = 0
DLine 2: n = len(nums)
Step-by-Step Solution
Solution:
  1. Step 1: Identify the range of numbers

    The array contains numbers from 0 to n, but the second loop only XORs numbers from 0 to n-1.
  2. Step 2: Spot the bug

    Line 6 loops from 0 to n-1, missing the number n, so if n is missing, it won't be XORed back.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Range should be 0 to n inclusive [OK]
Quick Trick: XOR all numbers including n, not just up to n-1 [OK]
Common Mistakes:
MISTAKES
  • Assuming range(n) includes n
  • Not considering missing number could be n
  • Ignoring off-by-one errors in loops
Trap Explanation:
PITFALL
  • Range excludes n, so missing number n is never XORed back.
Interviewer Note:
CONTEXT
  • Tests ability to detect off-by-one bugs in bitwise algorithms.
Master "Find the Missing Number" 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