I am working on a problem in which I am expected to take the xor of
all the pair of integers in an array and then find the K smallest
integers produced from xor’ing. The size of the array can be N=100000
and so K can be quite large but its limited to 250000.
For example,
if N=5 and K=4,
our array is {1 3 2 4 2}
The numbers resulting from xoring(1 and 3, 1-2, 1-4, 1-2, 3-2, 3-4, 3-2 etc)
3 3 2 5 0 1 6 1 6 7
Since K=4, we have to print 4 smallest integers.
so the answer would be 0 1 1 2.
Since the time limit is 2 sec and very tight, using the brute force approach
of xoring all the numbers would time out. My approach was wrong and so I need
help. May be we can exploit the limit on K=250000 and want to know if it is
possible to get the K smallest numbers without xoring all the integers.
Sorting your numbers in order would be a start, because the difference between the pairs will give you a lower bound for the xor, and therefore a cutoff point for when to stop looking for numbers to xor x with.
There is also a shortcut to looking for pairs of numbers whose xor is less than (say) a power of 2, because you’re only interested in x <= y <= x | (2 ^ N – 1). If this doesn’t give you enough pairs, increase N and try again.
EDIT: You can of course exclude the pairs of numbers that you already found whose xor is less than the previous power of 2, by using x | (2 ^ (N – 1) – 1) < y <= x | (2 ^ N) – 1.
Example based on (sorted) [1, 2, 2, 3, 4]
Start by looking for pairs of numbers whose xor is less than 1: for each number x, search for subsequent numbers y = x. This gives {2, 2}.
If you need more than one pair, look for pairs of numbers whose xor is less than 2 but not less than 1: for each number x, search for numbers x < y <= x | 1. This gives {2, 3} (twice).
Note that the final xor values aren’t quite sorted, but each batch is strictly less than the previous batch.
If you need more than that, look for pairs of numbers whose xor is less than 4 but not less than 2: for each number x, search for numbers x | 1 < y <= x | 3. This gives {1, 2} (twice); {1, 3}.
If you need more than that, look for pairs of numbers whose xor is less than 8 but not less than 4: for each number x, search for numbers x | 3 < y <= x | 7. This gives {1, 4}; {2, 4} (twice); {3, 4}.