Sum of squares of differences between all pairs of an array - GeeksforGeeks

29 Jan, 2022
Given an array arr[] of size N, the task is to compute the sum of squares of differences of all possible pairs.
Examples:
Input: arr[] = {2, 8, 4}Output: 56Explanation: Sum of squared differences of all possible pairs = (2 – 8)2 + (2 – 4)2 + (8 – 4)2 = 56
Input: arr[] = {-5, 8, 9, -4, -3}Output: 950
Naive Approach: The simplest approach is to generate all possible pairs and calculate the square of their differences of each pair and keep adding it to a variable, say sum. Finally, print the value of sum.
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The optimal idea is based on rearranging the expression in the following manner:
∑i=2 n ∑j=1i-1 (Ai-Aj)2 
Since Ai – Ai  = 0, the above expression can be rearranged as 1/2*(∑i=1n ∑j=1n (Ai-Aj)2) which can be further be simplified using the identity:
(A – B)2 = A2 + B2 – 2 * A * B 
As 1/2*(∑i=1n ∑j=1n (Ai2 + Aj2 – 2*Ai*Aj)) = 1/2 * (2*n*∑i=1n Ai2  – 2*∑i=1n (Aj * ∑j=1n Aj))
The final expression is n*∑i=1n Ai2 – (∑i=1nAi)2 which can be computed by linearly iterating over the array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate sum of squares// of differences of all possible pairsvoid sumOfSquaredDifferences(int arr[],                             int N){    // Stores the final sum    int ans = 0;     // Stores temporary values    int sumA = 0, sumB = 0;     // Traverse the array    for (int i = 0; i < N; i++) {        sumA += (arr[i] * arr[i]);        sumB += arr[i];    }     sumA = N * sumA;    sumB = (sumB * sumB);     // Final sum    ans = sumA - sumB;     // Print the answer    cout << ans;} // Driver Codeint main(){    // Given array    int arr[] = { 2, 8, 4 };     // Size of the array    int N = sizeof(arr) / sizeof(arr[0]);     // Function call to find sum of square    // of differences of all possible pairs    sumOfSquaredDifferences(arr, N);     return 0;}
// Java program for the above approachclass GFG{     // Function to calculate sum of squares// of differences of all possible pairsstatic void sumOfSquaredDifferences(int arr[],                                    int N){         // Stores the final sum    int ans = 0;     // Stores temporary values    int sumA = 0, sumB = 0;     // Traverse the array    for(int i = 0; i < N; i++)    {        sumA += (arr[i] * arr[i]);        sumB += arr[i];    }     sumA = N * sumA;    sumB = (sumB * sumB);     // Final sum    ans = sumA - sumB;     // Print the answer    System.out.println(ans);} // Driver Codepublic static void main (String[] args){         // Given array    int arr[] = { 2, 8, 4 };     // Size of the array    int N = arr.length;     // Function call to find sum of square    // of differences of all possible pairs    sumOfSquaredDifferences(arr, N);}} // This code is contributed by AnkThon
# Python3 program for the above approach # Function to calculate sum of squares# of differences of all possible pairsdef sumOfSquaredDifferences(arr, N):       # Stores the final sum    ans = 0     # Stores temporary values    sumA, sumB = 0, 0     # Traverse the array    for i in range(N):        sumA += (arr[i] * arr[i])        sumB += arr[i]     sumA = N * sumA    sumB = (sumB * sumB)     # Final sum    ans = sumA - sumB     # Print the answer    print(ans) # Driver Codeif __name__ == '__main__':       # Given array    arr = [2, 8, 4]     # Size of the array    N = len(arr)         # Function call to find sum of square    # of differences of all possible pairs    sumOfSquaredDifferences(arr, N) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System; class GFG{     // Function to calculate sum of squares// of differences of all possible pairsstatic void sumOfSquaredDifferences(int []arr,                                    int N){         // Stores the final sum    int ans = 0;     // Stores temporary values    int sumA = 0, sumB = 0;     // Traverse the array    for(int i = 0; i < N; i++)    {        sumA += (arr[i] * arr[i]);        sumB += arr[i];    }     sumA = N * sumA;    sumB = (sumB * sumB);     // Final sum    ans = sumA - sumB;     // Print the answer    Console.WriteLine(ans);} // Driver Codepublic static void Main(string[] args){         // Given array    int []arr = { 2, 8, 4 };     // Size of the array    int N = arr.Length;     // Function call to find sum of square    // of differences of all possible pairs    sumOfSquaredDifferences(arr, N);}} // This code is contributed by AnkThon
<script> // Javascript program for the above approach // Function to calculate sum of squares// of differences of all possible pairsfunction sumOfSquaredDifferences(arr, N){         // Stores the final sum    let ans = 0;     // Stores temporary values    let sumA = 0, sumB = 0;     // Traverse the array    for(let i = 0; i < N; i++)    {        sumA += (arr[i] * arr[i]);        sumB += arr[i];    }     sumA = N * sumA;    sumB = (sumB * sumB);     // Final sum    ans = sumA - sumB;     // Print the answer    document.write(ans);} // Driver Code // Given arraylet arr = [ 2, 8, 4 ]; // Size of the arraylet N = arr.length; // Function call to find sum of square// of differences of all possible pairssumOfSquaredDifferences(arr, N); // This code is contributed by subhammahato348 </script>
56
 
Time Complexity: O(N)Auxiliary Space: O(1) 
mohit kumar 29
ankthon
subhammahato348
saurabh1990aror
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples