Here is a mechanism that may not be as good as others, but that is instructive and comes to the bottom of why the XOR answer is as good as when k = 2.
1. Represent each number in base k. Support there are at most r digits in the representation 2. Add each of the numbers in the right-most ('r'th) digit mod k, then 'r - 1'st digit (mod k) and so on 3. The final representation of r digits that you have is the answer.
For example, if an array
A = {1, 2, 3, 4, 2, 3, 1, 2, 1, 3, 5, 4, 4}
The view in mod 3 has the form
A = {01, 02, 10, 11, 02, 10, 01, 02, 01, 10, 12, 11, 11} r = 2 Sum of 'r'th place = 2 Sum of the 'r-1'th place = 1
Therefore, answer = {12} in base 3 , which is 5 .
This is the answer that will be O(n * r) . Note that r proportional to log n .
Why is the XOR answer in O(n) ? Because the processor provides an XOR operation that runs in O(1) time, not the O(r) factor that we have above.
user1952500
source share