Given is an array of integers. Each number in the array occurs an ODD number of times, but only 1 number is occurring an EVEN number of times. Find that number.
Below is the solution I read on stackoverflow that does NOT work. I am unable to find the link to that solution and I was wondering if somebody could help me understand why this solution is incorrect unless I am doing something wrong below.
We first XOR all the elements in the array. Lets call it aWithOutDuplicate which contains all the odd elements except for duplicate one. We then OR all the elements. Lets call it aAllUniquethat should contain all the unique elements. XORing aWithOutDuplicate and aAllUniqueshould spit out the duplicate element.
int arr[] = {1,2,3,4,5,6,7,8,4,9};
int aWithOutDuplicate = 0;
int aAllUnique = 0;
for(int i=0;i<arr.length;i++) {
aWithOutDuplicate ^= arr[i];
aAllUnique |= arr[i];
}
cout << (aWithOutDuplicate ^ aAllUnique);
Update:
I wonder if this problem can be solved in O(n) time and O(1) space complexity.
That approach does not work because there is no way to differentiate a number that appears an even number of times from one that never appears at all. Consider this 4-bit example:
Now, add ANY number (<= 15 since it’s 4 bits) to the list twice. The or will stay the same because all the bits have been switched on and
0xf | x == 0xffor all 4-bit values of x. The xor will stay the same because0xf ^ x ^ x == 0xffor all values of x. So a counterexample to your method could be, e.g.{5, 10, 1, 1}.