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
- The two
41s and the two2s pair off, and4is the one left without a partner.
Example 2
- Input
- nums = [7]
- Output
- One value and no pairs at all, so it is itself the odd one out.
7
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