I have been asked this question in a job interview and I have been wondering about the right answer.
You have an array of numbers from 0 to n-1, one o
Scan the array 3 times:
A
. XOR together all the numbers from 0 to N-1 -> B
. Now A XOR B = X XOR D
, where X is the removed element, and D is the duplicate element.A XOR B
. XOR together all the array elements where this bit is set -> A1
. XOR together all the numbers from 0 to N-1 where this bit is set -> B1
. Now either A1 XOR B1 = X
or A1 XOR B1 = D
.A1 XOR B1
. If it is found, this is the duplicate element. If not, the duplicate element is A XOR B XOR A1 XOR B1
.