Is it possible to calculate the pairwise distance of a set of points in one dimension (all points are in a line) faster than O(n^2)?
Asked
Active
Viewed 975 times
-1
-
3Some information about the points and your `O(n^2)` approach would help. But as far as I can understand if you have to calculate for all pairs you will have to look at `n*(n-1)/2` pairs which would give `O(n^2)` complexity only. – Apurva Singh Oct 01 '19 at 07:22
-
Also the output is on size O(n²) therefore the algorithm cannot be faster than O(n^2) – MrSmith42 Oct 01 '19 at 07:55
-
1you should provide a clear statement of the problem, from what you wrote you can't do it in less than O(n^2) because you need to ask for the distance between any two points among all points and that will surely take O(n^2), if there is another requirement it could be done in less (if possible). – Nour Alhadi Mahmoud Oct 01 '19 at 08:12
2 Answers
1
We can make an algorithm in O(N) for calculating pair wise distance if the given points of the line are in a Array. The complexity of sorting will be Nlog(N) so overall complexity will be Nlog(N).
Store prefix sum of points after sorting in an array and total sum of points in a variable sum.
//suppose elements in the array is sorted and psum is prefix sum of array
ans=0, sum=psum[n-1]; //sum is total sum of points
for(i=0;i<n;i++)
ans+=((sum-psum[i]) - arr[i]*(n-i-1));
// (sum-psum[i]) will give the sum of all the numbers which are greater than arr[i]
// now we need to substract arr[i] (n-i-1) number of times
// all (n*n-n)/2 pairs distance will be calculated
cout<<ans;

Arjun Singh
- 387
- 3
- 9
0
It is obviously impossible to compute O(N²) distances in less than O(N²) operations.
If you only need some distances on-demand, you compute a single distance in O(1); do not precompute all of them.
If your question is in fact about the closest point pair, the 1D version is immediate: sort and find the closest successive points. The farthest point pair is even simpler: find the min and the max in time O(N). Or maybe you are after yet another problem...