Find the only integer in the array that’s not paired

Problem

In a given array of integers, each integer repeats itself except for one. Find that unpaired integer.

Example

[1,2,2,1,3] => 3


 

Solution

result = 0
for i in arr
  result ^= i
end
return result

 

Explanation

XOR operation is associative and commutative, so…

Given our solution, [1,2,2,1,3] will give
= 1 ^ 2 ^ 2 ^ 1 ^ 3
= 1 ^ 1 ^ 2 ^ 2 ^ 3
= (1 ^ 1) ^ (2 ^ 2) ^ 3
= 0 ^ 0 ^ 3
= 0 ^ 3
= 3

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s