In a list of numbers, every value appears exactly twice, except one value that appears once. Find the lone value.
What to build
Combine all the numbers with xor. Pairs cancel because x ^ x = 0, and the number that is left is the answer.
Requirements
- Use xor, in O(n) time and O(1) extra memory
- Use
long long
Input
The first line has n (odd). The second line has n numbers.
Output
The value that appears once.
Constraints
1 ≤ n ≤ 200,001 (odd). Numbers are between -10¹⁸ and 10¹⁸.
Example
Input:
5
4 1 2 1 2
Output:
4
Why it works
Xor is commutative and associative, so the order does not matter. Each pair cancels to 0, and 0 ^ x is x. The single number is what remains.
Examples
5 4 1 2 1 2
4
1 9
9
Hints
Hint 1
long long r = 0; then r ^= x for every x.
Hint 2
It works for negative numbers too, since xor treats them as bits.
Hint 3
No sorting or counting is needed.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
long long r = 0;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
r ^= x;
}
cout << r << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step