X or Problem (Algorithm)
X or Problem (Algorithm)
You are given an array of length n. Each number contained in the array has 2 occurrences,
except for one number which has 1 occurrence. Find the number in O(n) time.
1.1 XOR
XOR stands for exclusive or. For this problem, we are concerned with Bitwise XOR, which
is implemented in C with the operator.
Input Output
0 0 0
0 1 1
1 0 1
1 1 0
Table 1.1: Truth table for XOR
We can also compute the XOR of numbers other than 0 and 1. Consider for example 3 5.
This can be written in binary as 011 101. We can evaluate this as
0 1 1
1 0 1
1 1 0
Table 1.2: XOR operation (3 5)
where 110 can be written as 6 when converted to base
10
. The easiest way to perform the
binary conversion is shown below.
16 8 4 2 1
3 1 1
5 1 0 1
Table 1.3: Base 10 to binary conversion
The solution for this problem uses the fact that x x = 0, which implies that x y x =
x x y = y. In other words, rearranging the order of XOR operations does not change the
net result. This is illustrated in Table 4 using 3 5 3 as an example.
1.1.1 XOR solution
The algorithm for this solution is to simply perform XOR operations on each element in the
numeric array until the end of the array has been reached. The order of the operations does
not matter as long as each element is used in an XOR operation. For testing purposes, the
following array will be used
1
0 1 1
1 0 1
1 1 0
0 1 1
1 0 1
0 1 1
0 1 1
0 0 0
1 0 1
1 0 1
Table 1.4: Illustrating that 3 5 3 = 3 3 5 = 5
int nums[11] = {3, 5, 7, 6, 7, 5, 3, 8, 8, 9, 6};
This array will then be used as a parameter for the ndSingle(int nums[ ], int n) function,
where nums[ ] is the array parameter and n is the length of the numeric array. The code is
shown below.
// xor.c
#include <stdlib.h>
#include <stdio.h>
int findSingle(int nums[], int n) {
int ans, i;
for(i = 0; i < n; i++) ans = ans^nums[i];
return(ans);
}
int main() {
int nums[11] = {3,5,7,6,7,5,3,8,8,9,6};
findSingle(nums, 11);
}
When this code is run, ndSingle(nums, 11) returns 9 as it should.
1.2 Alternative solution
This problem could also be solved (though not in O(n) time) by sorting the array. Then
the function would go through the sorted array (and declare a previous number variable and
counter variable to 0 before it does). It would then keep track of the rst element of the
(sorted) array since the counter is equal to 0. As it does this, it will also add the counter
variable to itself so that the counter variable is now 1 and set the previous number variable
to the current number (i.e. nums[0]). When it reaches the second element of the array, it
would check whether the current element equals to the previous number variable. If it does
not it will return the previous number variable. If it does, it will set the counter variable
to 0. Eventually the single number will be returned. Note that this solution is much slower
than the XOR solution.
2