We can find the non-repeating number in an array where every other element repeats twice using bit manipulation. This can be achieved using the XOR bitwise operator.
The XOR operation ("exclusive or") is a binary operation that takes two bits and returns 1 if exactly one of the bits is 1. In other words, it returns true if the two bits are opposite.
The XOR operation has two properties which are very useful in this context:
1) βA XOR A = 0β
2) βA XOR 0 = Aβ
3) βA XOR B XOR A = Bβ
If we XOR all elements in the array, all the elements which are repeated twice will become 0 (because βA XOR A = 0β), and we are left with the element which is only present once as the result.
Suppose we have an array βarr[] = 2, 3, 5, 4, 5, 3, 4β.
If we XOR all the numbers together:
β(2 3Μ 5Μ 4Μ 5Μ 3Μ 4Μ)β
We can reorder as:
β((2 2Μ) (Μ3 3Μ) (Μ4 4Μ) (Μ5 5Μ)) 5Μβ
Each pair of the same number will XOR to 0, leaving us with:
β0 5Μβ
Remember βA XOR 0 = Aβ, therefore we get β5β which is the number that has no duplicate in the array.
A Python example code:
def find_single(nums):
res = 0
for num in nums:
res ^= num
return res
For an array βarr[] = 2, 3, 5, 4, 5, 3, 4β, calling βfind_single(arr)β would return β5β.