Problem Description
You are given a non-empty integer array nums in which every element appears twice except for one.
Find that single element.
You must implement a solution with linear time complexity and constant extra space.
Constraints
- The array contains from 1 to 3 * 104 elements
- Each element is in the range from -3 * 104 to 3 * 104
- Each element appears twice except for one
Examples
Input: [2, 2, 1]
Answer: 1
Hash table approach
The first idea that comes to mind is a classic array traversal that counts the frequency of each number.
For each number we store a pair in a hash table, where the key is the number itself and the value is how many times it appears in the array.
At the end, we just scan the table and pick the number whose counter equals 1.
Here's that solution.
export const singleNumberMap = (nums: number[]): number => {
const countMap: Record<number, number> = {};
nums.forEach((num) => {
const curr = countMap[num] ?? 0;
countMap[num] = curr + 1;
});
const entries = Object.entries(countMap);
for (let i = 0; i < entries.length; i++) {
const [num, count] = entries[i];
if (count === 1) {
return Number(num);
}
}
return 0;
};However, this solution doesn't fit the requirements, because storing frequencies in a hash table gives us linear space complexity.
XOR approach
The problem is actually very easy, but you need to know a trick: how the XOR operation works.
XOR is the logical exclusive or operation (denoted ⊕), and it has several useful properties we can take advantage of.
a ⊕ a = 0: applying exclusive or to identical bits yields zero.b ⊕ 0 = b: if one of the bits is0, the result is the other bit.a ⊕ b ⊕ a = a ⊕ a ⊕ b: XOR is commutative, so we can change the order of operations.
This gives us a simple solution:
a ⊕ b ⊕ a = (a ⊕ a) ⊕ b = 0 ⊕ b = b
So all we need to do is XOR all elements of the array together. Pairs of equal values cancel each other out, and the result of the XOR is the single number itself.
export const singleNumber = (nums: number[]): number => {
let res = 0;
nums.forEach((num) => {
res ^= num;
});
return res;
};Complexity Analysis
n is the number of elements in the array.
Time Complexity
O(n), since we iterate over all elements of the array.
Space Complexity
O(1), since we don't create any additional data structures.