Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all possible distances from two arrays

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.

like image 854
Karsten Ari Agathon Avatar asked Dec 15 '15 08:12

Karsten Ari Agathon


People also ask

How do you find the maximum distance between two elements in an array?

A simple solution for this problem is to, one by one, pick each element from the array and find its first and last occurrence in the array and take the difference between the first and last occurrence for maximum distance. The time complexity for this approach is O(n2).

How do you find the Euclidean distance between two arrays?

In this method, we first initialize two numpy arrays. Then, we take the difference of the two arrays, compute the dot product of the result, and transpose of the result. Then we take the square root of the answer. This is another way to implement Euclidean distance.

How do you find the distance between two arrays in Python?

Use the math. dist() Function to Find the Euclidean Distance Between Two Points. The math module also can be used as an alternative. The dist() function from this module can return the line segment between two points.

How do I find the distance between two functions?

Distance formula: d = sqrt{ (x_2 - x_1)^2 + (y_2 - y_1)^2 }


1 Answers

You can get a O(MlogM) complexity solution in the following way.

  1. Prepare an array Ax of length M with Ax[i] = 1 if i belongs to A (and 0 otherwise)
  2. Prepare an array Bx of length M with Bx[M-1-i] = 1 if i belongs to B (and 0 otherwise)
  3. Use the Fast Fourier Transform to convolve these 2 sequences together
  4. Inspect the output array, non-zero values correspond to possible distances

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.

like image 54
Peter de Rivaz Avatar answered Oct 04 '22 05:10

Peter de Rivaz