Let's Learn it Together !

ِAn educational blog from FCIS'2011 students ..

Question


Find an O(n) algorithm for finding an integer that occurs only once in a list which has all other integers occurring exactly twice. So, in this list of integers, each integer repeats exactly twice, except one. To find that one, what is the best algorithm?


List: 2 2 7 3 1 7 1.

Answer: 3.



Answer


Just XOR all of them…


a XOR b XOR a XOR c XOR b XOR c ... XOR z
= (a XOR a) XOR (b XOR b) XOR ... XOR z
= 0 XOR 0 XOR ... XOR z
= z



Thanks to F.M.A.R. who sent me this problem.

This is the pdf version of this article.

7 comments:

Interesting! really a new approach for thinking (Y)

لأ حلوة :D
Abu-Bakr Taha

la2 begad gamda thx ya dr

Proud To Be Muslim said...

ok actually we can make it using some memory

make an array with largest number and index it
if its Value is one that means it has been accesed before and since each number occurs only twice then this isnt our disered else then increment the index and continue looping

better one we can use hashing if this key is already existed then remove it
else create index and increment it by one
the last key reamining is the disered number

Proud To Be Muslim said...

or actually a boolean array :D would be much better

Regarding your first solution, if the whole problem contained 3 numbers: 1, 2000000000 and 2000000000. Is it worth to reserve 2000000000 units of memory to solve a problem with 3 numbers?!

يا ريت يا دكتور مسائل زي ده كتير انا بحب المسائل اللي فيها حركات زي ده
بس مش حركات و خلص لأ زي ده حركات بستخدم فيها
Math, Logic, etc

Post a Comment