How do you do this? The values are unsorted but are of [1..n]
Example array [3,1,2,5,7,8]
. Answer: 4, 6
I saw this solution in
This method is not advisable as it suffers from integer
overflow problems. So use XOR
method to find the two numbers, which is highly performant. If you are interested i can explain.
As per the request from @ordinary below, i am explaining the algorithm:
EDIT
Suppose the maximum element of the array a[]
is B
i.e. suppose a[]={1,2,4}
and here 3
and 5
are not present in a[] so max element is B=5
.
xor
all the elements of the array a
to X
xor
all the elements from 1 to B
to x
x
by x = x &(~(x-1));
a[i] ^ x == x
than xor
a[i]
to p
else xor
with q
k
from 1 to B
if k ^ x == x
than xor
with p
else xor
with q
p
and q
proof:
Let a = {1,2,4}
and B
is 5 i.e. from 1 to 5 the missing numbers are 3 and 5
Once we XOR
elements of a
and the numbers from 1 to 5 we left with XOR
of 3 and 5 i.e. x
.
Now when we find the leftmost bit set of x
it is nothing but the left most different bit among 3 and 5. (3--> 011
, 5 --> 101
and x = 010
where x = 3 ^ 5
)
After this we are trying to divide into two groups according to the bit set of x
so the two groups will be:
p = 2 , 2 , 3 (all has the 2nd last bit set)
q = 1, 1, 4, 4, 5 (all has the 2nd last bit unset)
if we XOR
the elements of p
among themselves we will find 3
and similarly if we xor
all the elements of q
among themselves than we will get 5.
Hence the answer.
code in java
public void findNumbers(int[] a, int B){
int x=0;
for(int i=0; i