The magic of XOR

  • Share this:
The magic of XOR

How to find the unique element in an array super-fast using XOR operation.

Given an array of elements where each element occurs twice except one element, how do you find the element which occurs only once?

Well, the obvious way is to loop through the array and keep track of how many time each element occurs.

But there is an even simpler and faster way to find the required element. The secret lies in the unique property of XOR.

The truth table of XOR is

Truth Table
I1I2OP
000
011
100
110

The output is set only when one of the inputs is 1. This gives rise to some unique results which are very useful.

We will use the symbol to denote XOR, which is used in most programming languages. Let n be any number then,

  • n ^ 0 = n
  • n ^ n = 0

This means if we XOR all the elements of the array, We will be left with the element which occurs only once since the duplicate elements cancel each other.

Example : 

consider the array 

[ 2, 2, 4, 5, 4, 7, 8, 8, 7]
2 ^ 2 ^ 4 ^ 5 ^ 4 ^ 7 ^ 8 ^ 8 ^ 7 = 5


Python Code :

a = [2,2,3,5,6,5,7,8,8,7,3]

result = 0

for i in a: 

    result ^= i

print(result)

Output : 

6

Powered by Froala Editor

profile.png

Ben Meehan

About author
Software Engineer at Ather Energy. Enjoy Competitive Programming and Blogging. Worked as an technical author intern at OpenGenus.org
Ben Meehan - OpenGenus
0 Comments
Leave a Comment