Find XOR of Numbers Twice
You are given an array nums where each integer appears at most twice. Return the XOR of all numbers that appear exactly twice.
Examples
Input: [1,2,1,3]
Output: 1
Input: [1,2,3,2,4,4]
Output: 6
Hints
Instead of using a frequency map, observe that XORing a number with itself cancels it out (results in 0). Use this property to track numbers that appear twice by XORing all elements and then XORing the result with the XOR of all numbers in `[1, n]`.
Leverage the fact that the array length is `2n` and each number in `[1, n]` appears at most twice. Compute the XOR of all elements in the array and the XOR of all numbers in `[1, n]`. The result is the XOR of numbers appearing twice.
Optimize space by using a single variable to track the XOR of numbers seen twice. Iterate through the array, and for each number, XOR it with a running result if it has been seen before (use a set or a boolean array to track seen numbers).
Related Problems
Find XOR of Numbers Twice
You are given an array nums where each integer appears at most twice. Return the XOR of all numbers that appear exactly twice.