Find odd occurring element in an array in single traversal

Given an array of integers, duplicates are present in it in such a way that all duplicates appear even number of times except one which appears odd number of times. Find that odd appearing element in linear time and without using any extra memory.


 
For example,


Input: arr = [4, 3, 6, 2, 6, 4, 2, 3, 4, 3, 3]

Output: Odd occurring element is 4

 


 

We can use hashing to solve this problem in O(n) time. We initially traverse the array and maintain frequency of each element in a hash table. Then after all array elements are processed, we return the element with the odd frequency. The problem with this approach is that it requires O(n) extra space as well. Also it requires one traversal of array and one traversal of hash table.
 

We can solve this problem in one traversal of array and in O(1) space. The idea is to use XOR operator. We know that if we XOR a number with itself odd number of times the result is number itself, otherwise if we XOR a number even number of times with itself, the result is 0. Also XOR with 0 is always the number itself.


XOR x with 0
x ^ 0 = x
 

XOR x with itself even number of times
x ^ x = 0
x ^ x ^ x ^ x = (x ^ x) ^ (x ^ x) = 0 ^ 0 = 0
 

XOR x with itself odd number of times
(x ^ x ^ x) = (x ^ (x ^ x)) = (x ^ 0) = x
(x ^ x ^ x ^ x ^ x) = (x ^ (x ^ x) ^ (x ^ x)) = (x ^ 0 ^ 0) = x

 

So, if we take XOR of all elements present in the array, even appearing elements will cancel each other and we are left with the only odd appearing element.

 
C implementation –
 

Download   Run Code

Output:

Odd occurring element is 4

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
Sort by:   newest | oldest | most voted
Marco
Marco

Hi, just a solution using std::accumulate and std::bit_xor:
https://ideone.com/LEqki6

MalayaZemlya
MalayaZemlya

It is also possible to solve the problem in linear time if there are two unpaired elements.
You’ll need more than one pass, but the total is still O(n)

wpDiscuz