Here's a way: The base 2 xor operator has an obvious extension to base 3 such that for all integers N, N ^ N ^ N = 0, just like the normal xor has N ^ N = 0.
This base 3 operator a^b just adds corresponding digit pairs of a and b mod 3 to get the digits of the result. So the algorithm is to convert each input number to base 3 and tally up the total with the base 3 ^ operator. The result will be the answer in base 3. The example above in base 3 is 2,1,11,12,1,11,2,2,11,1 Running total with ^: 0 ^ 2 = 2 2 ^ 1 = 0 0 ^ 11 = 11 11 ^ 12 = 20 20 ^ 1 = 21 21 ^ 11 = 2 2 ^ 2 = 1 1 ^ 2 = 0 0 ^ 11 = 11 11 ^ 1 = 12 And 12 is 5 base 3. The total will never have more digits than the biggest number. This is O(1) space. You have to assume base 3 conversion is a constant time operation, but this is pretty reasonable. If the problem changes to "all the numbers are repeated K times except for one, which appears only once, you can do the same thing with base K to get the answer. On Sep 11, 2:10 pm, Neha Singh <[email protected]> wrote: > You are given an array that contains integers. The integers content is such > that every integer occurs 3 times in that array leaving one integer that > appears only once. > Fastest way to find that single integer > eg: > Input: [2,1,4,5,1,4,2,2,4,1] > Answer: 5 > > The solution must be of O(n) time and O(1) space -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.
