How to find two non-repeating numbers in an array
Problem Statement
We have 2*N +2 numbers. In this expression, every number comes twice except two numbers which occur once.
Find these two numbers.
Pre-Requisites
Problem Explanation
Let two numbers that occur once be a and b. The array be a list of 2*N+2 numbers.
-
N=2,array= [2, 1, 3, 5, 1, 3]-
In this example, {1, 3} occur twice and {2, 5} occur once.
-
Thus,
a= 2 andb= 5
-
-
N=3,array= [1, 10, 10, 1, 5, 6, 5, 9]-
a= 6 -
b= 9
-
Solution
Let a and b be the two unique numbers.
We’ll first calculate the res and cumulative XOR of the array.
We know that the XOR of any number occurring even times is 0. Moreover, every number except a and b occur twice.
Thus, effectively res = a^b.
Now, a fundamental observation is:
- We know, res =
a^b.
Note: If the
ith bit ofresis set, theith bit ofaand theith bit ofbmust be different.
We’ll split the main array into two arrays (array1 and array2).
-
array1= List of numbers ofarraywhich have theirith bit same asith bit ofa. -
array2= List of numbers ofarraywhich have theirith bit same asith bit ofb.
The cumulative XOR of array1 will give us the value of a, and the cumulative XOR of array2 will provide us with the value of b.
N = 3array = [1, 10, 10, 1, 5, 6, 5, 9]a,b = 0,0res = 0for v in array:res = res^vlsb = 0while (True):if ((res>>lsb)&1): breaklsb+=1for v in array:if ((v>>lsb)&1): a^=velse: b^=vprint(a,b)
Explanation
-
Line 1: We take
Nas input. -
Line 2: We take 2*
N+2 numbers as input and store them in anarray. -
Lines 3–4: We initialize two unique numbers (
a,b) and cumulative XOR ofarrayandresto0. -
Line 6: We loop over every value
vof the array to calculateres. -
Line 9: We initialize
lsb(the least significant bit) to0. -
Lines 10–12: We start the
whileloop to calculatelsbofres. -
Lines 15–17: We loop over every value
vof thearray.-
Line 16: If the
lsbth bit ofvis set, then we performa = a^v, since we wantato be the cumulative XOR of all numbers in array with theirlsbbit set. -
Line 17: If the
lsbth bit ofvis off, thenb = b^v.
-
-
Line 19: Consequently, the first unique number will be
a, and the second unique number will beb.