Search code examples
functionoperatorsxor

Three-way xor-like function


I'm trying to solve the following puzzle:

Given a stream of numbers (only 1 iteration over them is allowed) in which all numbers appear 3 times, but 1 number appear only 2 times, find this number, using O(1) memory.

I started with the idea that, if all numbers appeared 2 times, and 1 number only once, I could use xor operation between all numbers and the result would be the incognito number.

So I want to extend this idea to solve the puzzle. All I need is a xor-like function (or operator), which would yield 0 on the third apply:

SEED xor3 X xor3 X xor3 X = SEED

X xor3 Y xor3 SEED xor3 X xor3 Y xor3 Y xor3 X = SEED

Any ideas for such a function?


Solution

  • Regard XOR as summation on each bit of a number expressed in binary (i.e. a radix of 2), modulo 2.

    Now consider a numerical system consisting of tribits 0, 1, and 2. That is, it has a radix of 3.

    The operator T now becomes an operation on any number, decomposed into this radix. As in XOR, you sum the bits, but the difference is that operator T is ran in modulo 3.

    You can easily show that a T a T a is zero for any a. You can also show that T is both commutative and associative. That is necessary since, in general, your sequence will have the numbers jumbled up.

    Now apply this to your list of numbers. At the end of the operation, the output will be b where b = o T o and o is the number that occurs exactly twice.