# Sum of squares of distances between all pairs from given points

Given an array arr[] consisting of coordinates of N points on an XY-plane, the task is to find the sum of squared distances between all pairs of points, i.e. (Xi – Xj)2 + (Yi – Yj)2 for every distinct pair (i, j).

Examples:

Input: arr[][] = {{1, 1}, {-1, -1}, {1, -1}, {-1, 1}}Output: 32Explanation:Distance of 1st point (1, 1) from the 2nd, 3rd and 4th points are 8, 4 and 4 respectively.Distance of 2nd point from the 3rd and 4th points are 4 and 4 respectively.Distance of 3rd point from the 4th point is 8.Therefore, the total distance = (8 + 4 + 4) + (4 + 4) + (8) = 32

Input: arr[][] = {{1, 1}, {1, 1}, {0, 0}}Output: 4Explanation:Distance of 1st point from the 2nd and 3rd points are 0 and 2 respectively.Distance of 2nd point from the 3rd point is 2.Therefore, the total distance = (0 + 2) + (2) = 4

Naive Approach: The simplest approach to solve the problem is to generate all possible distinct pairs of the given array arr[][] and calculate the sum of squares of distances between all pairs of points (Xi, Yj) and (Xj, Yj), i.e. (Xi – Xj)2 + (Yi – Yj)2, for every distinct pair (i, j).Time Complexity: O(N2)Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to regroup the sum and split the sum of squares of distances into two sums. Follow the steps below to solve the problem:Initialize variables, say xq, yq, xs, and ys.

Initialize a variable, say res, with zero, to store the resultant sum.

Traverse the given array and for each point {x, y}, perform the following steps:

Add the value of (i*x2 + i*y2) in the variable res, which corresponds to adding of squared distance.

Add the value (xq – 2 * xs * a) and (yq – 2 * ys * b) to res to nullify the effect of the 2 * X * Y in the expansion of (a – b)2.

Add the values a2 and b2 to variables xq and yq respectively.

Add the values a and b to variables xs and ys respectively.

Add the values xs and yq to variables a2 and b2 respectively.

After completing the above steps, print the value of res as the result.

Below is the implementation of the above approach:

C++

#include

using namespace std;

void findSquareSum(

int Coordinates[][2], int N)

{

long long xq = 0, yq = 0;

long long xs = 0, ys = 0;

long long res = 0;

for (int i = 0; i < N; i++) {
int a, b;
a = Coordinates[i][0];
b = Coordinates[i][1];
res += xq;
res -= 2 * xs * a;
res += i * (long long)(a * a);
xq += a * a;
xs += a;
res += yq;
res -= 2 * ys * b;
res += i * (long long)b * b;
yq += b * b;
ys += b;
}
cout