by ardit33 · 18y ago · 0 comments
"What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice. So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm."
I want the hacker community to answer this question (which seems more like a typical interview question). Ideas?
# associative array / dict / hash
store = {}
for elem in inputlist:
if elem in store:
del store[elem]
else:
store[elem] = True
# return the only key left
return store.keys()[0]
Now that I've looked at the post, the XOR approach is quite efficient and a more fun answer. x ^ y ^ y ^ x ^ z
= x ^ x ^ y ^ y ^ z
= 0 ^ 0 ^ z
= z >>> import random, operator
>>> nums = (range(5)*2)
>>> random.shuffle(nums)
>>> nums.pop()
1
>>> nums
[0, 4, 0, 3, 2, 4, 3, 1, 2]
>>> reduce(operator.xor, nums)
1 import operator
answer = reduce(operator.xor, nums)