Reputation: 123
Given two sorted array A
and B
length N. Each elements may contain natural number less than M
. Determine all possible distances for all combinations elements A
and B
. In this case, if A[i] - B[j] < 0
, then the distance is M + (A[i] - B[j])
.
Example :
A = {0,2,3}
B = {1,2}
M = 5
Distances = {0,1,2,3,4}
Note: I know O(N^2)
solution, but I need faster solution than O(N^2)
and O(N x M)
.
Edit: Array A
, B
, and Distances
contain distinct elements.
Upvotes: 6
Views: 184
Reputation: 9065
You can use bitvectors to accomplish this. Bitvector operations on large bitvectors is linear in the size of the bitvector, but is fast, easy to implement, and may work well given your 50k size limit.
Initialize two bitvectors of length M. Call these vectA and vectAnswer. Set the bits of vectA that correspond to the elements in A. Leave vectAnswer with all zeroes.
Define a method to rotate a bitvector by k elements (rotate down). I'll call this rotate(vect,k).
Then, for every element b of B, vectAnswer = vectAnswer | rotate(vectA,b).
Upvotes: 0
Reputation: 2857
I possible done with optimized N*N.
If convert A to 0 and 1 array where 1 on positions which present in A (in range [0..M]. After convert this array into bitmasks, size of A array will be decreased into 64 times.
This will allow insert results by blocks of size 64.
Complexity still will be N*N
but working time will be greatly decreased. As limitation mentioned by author 50000 for A and B sizes and M.
Expected operations count will be N*N/64 ~= 4*10^7. It will passed in 1 sec.
Upvotes: 0
Reputation: 33499
You can get a O(MlogM) complexity solution in the following way.
Note that the FFT is normally done with floating point numbers, so in step 4 you probably want to test if the output is greater than 0.5 to avoid potential rounding noise issues.
Upvotes: 5