Single number (XOR)

Easy TimeO(n) SpaceO(1)

An array nums holds values where every one appears exactly twice, except a single value that appears once. Return that value, using extra memory that does not grow with the length of the array. The array is not sorted.

Examples

Example 1

Input
nums = [4, 1, 2, 1, 2]
Output
4
The two 1s and the two 2s pair off, and 4 is the one left without a partner.

Example 2

Input
nums = [7]
Output
7
One value and no pairs at all, so it is itself the odd one out.

The Code

function singleNumber(nums) {
  let result = 0;
  for (let i = 0; i < nums.length; i++) {
    result = result ^ nums[i];
  }
  return result;
}
singleNumber([4, 1, 2, 1, 2]);
Done
Step through singleNumber([4, 1, 2, 1, 2]) call by call