Sum of absolute differences of all pairs in a given array
Last Updated :
23 Apr, 2023
Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array.
Examples:
Input : arr[] = {1, 2, 3, 4}
Output: 10
Sum of |2-1| + |3-1| + |4-1| +
|3-2| + |4-2| + |4-3| = 10
Input : arr[] = {1, 8, 9, 15, 16}
Output: 74
Input : arr[] = {1, 2, 3, 4, 5, 7, 9, 11, 14}
Output: 188
A simple solution for this problem is to one by one look for each pair take their difference and sum up them together. The time complexity for this approach is O(n2).
C++
// C++ program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
#include<bits/stdc++.h>
using namespace std;
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
int sumPairs(int arr[],int n)
{
// final result
int sum = 0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
sum+=abs(arr[i]-arr[j]);
}
}
return sum;
}
// Driver program to run the case
int main()
{
int arr[] = {1, 8, 9, 15, 16};
int n = sizeof(arr)/sizeof(arr[0]);
cout << sumPairs(arr, n);
return 0;
}
// This code is contributed by Pushpesh Raj.
Java
// Java program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
class GFG {
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
static int sumPairs(int arr[], int n)
{
// final result
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
}
return sum;
}
// Driver program to run the case
public static void main(String[] args)
{
int arr[] = { 1, 8, 9, 15, 16 };
int n = arr.length;
System.out.println(sumPairs(arr, n));
}
}
// This code is contributed by karandeep1234.
Python3
# Python3 program to find sum of absolute differences
# in all pairs in a sorted array of distinct numbers
# Function to calculate sum of absolute difference
# of all pairs in array
# arr[] --> array of elements
def sumPairs(arr, n):
# final result
sum = 0;
for i in range(n):
for j in range(i + 1, n):
sum += abs(arr[i]-arr[j]);
return sum;
# Driver program to run the case
arr = [1, 8, 9, 15, 16];
n = len(arr);
print(sumPairs(arr, n));
# This code is contributed by phasing17
C#
// C# program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
using System;
class GFG {
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
static int sumPairs(int[] arr, int n)
{
// final result
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
sum += Math.Abs(arr[i] - arr[j]);
}
}
return sum;
}
// Driver program to run the case
public static void Main(string[] args)
{
int[] arr = { 1, 8, 9, 15, 16 };
int n = arr.Length;
Console.WriteLine(sumPairs(arr, n));
}
}
// This code is contributed by phasing17.
JavaScript
// JS program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
function sumPairs(arr, n)
{
// final result
let sum = 0;
for(var i=0;i<n;i++)
{
for(var j=i+1;j<n;j++)
{
sum+= Math.abs(arr[i]-arr[j]);
}
}
return sum;
}
// Driver program to run the case
let arr = [1, 8, 9, 15, 16];
let n = arr.length;
console.log(sumPairs(arr, n));
// This code is contributed by phasing17
The space complexity of this program is O(1), because it does not use any extra space that depends on the input size. The only space used is for the input array, which has a fixed size of n, so the space complexity is constant.
An efficient solution for this problem needs a simple observation. Since array is sorted and elements are distinct when we take sum of absolute difference of pairs each element in the i'th position is added 'i' times and subtracted 'n-1-i' times.
For example in {1,2,3,4} element at index 2 is arr[2] = 3 so all pairs having 3 as one element will be (1,3), (2,3) and (3,4), now when we take summation of absolute difference of pairs, then for all pairs in which 3 is present as one element summation will be = (3-1)+(3-2)+(4-3). We can see that 3 is added i = 2 times and subtracted n-1-i = (4-1-2) = 1 times.
The generalized expression for each element will be sum = sum + (i*a[i]) - (n-1-i)*a[i].
C++
// C++ program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
#include<bits/stdc++.h>
using namespace std;
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
int sumPairs(int arr[],int n)
{
// final result
int sum = 0;
for (int i=n-1; i>=0; i--)
sum += i*arr[i] - (n-1-i)*arr[i];
return sum;
}
// Driver program to run the case
int main()
{
int arr[] = {1, 8, 9, 15, 16};
int n = sizeof(arr)/sizeof(arr[0]);
cout << sumPairs(arr, n);
return 0;
}
// This code is contributed by Sania Kumari Gupta
C
// C program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
#include <stdio.h>
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
int sumPairs(int arr[], int n)
{
// final result
int sum = 0;
for (int i = n - 1; i >= 0; i--)
sum += i * arr[i] - (n - 1 - i) * arr[i];
return sum;
}
// Driver program to run the case
int main()
{
int arr[] = { 1, 8, 9, 15, 16 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", sumPairs(arr, n));
return 0;
}
// This code is contributed by Sania Kumari Gupta
Java
// Java program to find sum of absolute differences in all
// pairs in a sorted array of distinct numbers
class GFG {
// Function to calculate sum of absolute
// difference of all pairs in array
// arr[] --> array of elements
static int sumPairs(int arr[], int n)
{
// final result
int sum = 0;
for (int i = n - 1; i >= 0; i--)
sum += i * arr[i] - (n - 1 - i) * arr[i];
return sum;
}
// Driver program
public static void main(String arg[])
{
int arr[] = { 1, 8, 9, 15, 16 };
int n = arr.length;
System.out.print(sumPairs(arr, n));
}
}
// This code is contributed by Sania Kumari Gupta
Python3
# Python3 program to find sum of
# absolute differences in all pairs
# in a sorted array of distinct numbers
# Function to calculate sum of absolute
# difference of all pairs in array
# arr[] --> array of elements
def sumPairs(arr, n):
# final result
sum = 0
for i in range(n - 1, -1, -1):
sum += i*arr[i] - (n-1-i) * arr[i]
return sum
# Driver program
arr = [1, 8, 9, 15, 16]
n = len(arr)
print(sumPairs(arr, n))
# This code is contributed by Anant Agarwal.
C#
// C# program to find sum of absolute
// differences in all pairs in a sorted
// array of distinct numbers
using System;
class GFG {
// Function to calculate sum of absolute
// difference of all pairs in array
// arr[] --> array of elements
static int sumPairs(int []arr, int n)
{
// final result
int sum = 0;
for (int i = n - 1; i >= 0; i--)
sum += i * arr[i] - (n - 1 - i)
* arr[i];
return sum;
}
// Driver program
public static void Main()
{
int []arr = { 1, 8, 9, 15, 16 };
int n = arr.Length;
Console.Write(sumPairs(arr, n));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find sum of absolute differences
// in all pairs in a sorted array of distinct numbers
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
function sumPairs($arr,$n)
{
// final result
$sum = 0;
for ($i=$n-1; $i>=0; $i--)
$sum = $sum + $i*$arr[$i] - ($n-1-$i)*$arr[$i];
return $sum;
}
// Driver program to run the case
$arr = array(1, 8, 9, 15, 16);
$n = sizeof($arr)/sizeof($arr[0]);
echo sumPairs($arr, $n);
?>
JavaScript
<script>
// JavaScript program to find
// sum of absolute differences
// in all pairs in a sorted array
// of distinct numbers
// Function to calculate sum of absolute difference
// of all pairs in array
// arr[] --> array of elements
function sumPairs( arr, n)
{
// final result
let sum = 0;
for (let i=n-1; i>=0; i--)
sum += i*arr[i] - (n-1-i)*arr[i];
return sum;
}
// Driver program to run the case
let arr = [ 1, 8, 9, 15, 16 ];
let n = arr.length;
document.write(sumPairs(arr, n));
</script>
Time Complexity: O(n)
Auxiliary space: O(1)
What if array is not sorted?
The efficient solution is also better for the cases where array is not sorted. We can sort the array first in O(n Log n) time and then find the required value in O(n). So overall time complexity is O(n Log n) which is still better than O(n2)
Below is the code for above approach.
C++
// C++ program for above approach
#include<bits/stdc++.h>
using namespace std;
// Function to calculate sum of absolute
// difference of all pairs in array
int sumPairs(int arr[], int n)
{
// sorting the array
sort(arr, arr+n);
// Initialising the variable
// to store the sum
int sum = 0;
// Iterating through each element
// and adding it i times and
// subtracting it (n-1-i) times
for(int i = 0; i < n; i++){
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
// Driver program
int main()
{
int arr[] = {16, 8, 9, 1, 15};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<sumPairs(arr, n);
return 0;
}
Java
// Java program for above approach
import java.util.Arrays;
public class Main {
// Function to calculate sum of absolute
// difference of all pairs in array
static int sumPairs(int[] arr, int n) {
// sorting the array
Arrays.sort(arr);
// Initialising the variable
// to store the sum
int sum = 0;
// Iterating through each element
// and adding it i times and
// subtracting it (n-1-i) times
for(int i = 0; i < n; i++) {
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
// Driver program
public static void main(String[] args) {
int[] arr = {16, 8, 9, 1, 15};
int n = arr.length;
System.out.println(sumPairs(arr, n));
}
}
// This code is contributed by bhardwajji
Python3
# Python program for above approach
# Function to calculate sum of absolute
# difference of all pairs in array
def sumPairs(arr, n):
# sorting the array
arr.sort()
# Initialising the variable
# to store the sum
sum = 0
# Iterating through each element
# and adding it i times and
# subtracting it (n-1-i) times
for i in range(n):
sum += i*arr[i] - (n-1-i)*arr[i]
return sum
# Driver program
arr = [16, 8, 9, 1, 15]
n = len(arr)
print(sumPairs(arr, n))
# This code is contributed by Aman Kumar.
C#
using System;
class Program {
// Function to calculate sum of absolute
// difference of all pairs in array
static int SumPairs(int[] arr, int n)
{
// sorting the array
Array.Sort(arr);
// Initialising the variable
// to store the sum
int sum = 0;
// Iterating through each element
// and adding it i times and
// subtracting it (n-1-i) times
for(int i = 0; i < n; i++){
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
// Driver program
static void Main(string[] args) {
int[] arr = {16, 8, 9, 1, 15};
int n = arr.Length;
Console.WriteLine(SumPairs(arr, n));
}
}
// This code is contributed by divyansh2212
JavaScript
// JavaScript program for above approach
// Function to calculate sum of absolute
// difference of all pairs in array
function sumPairs(arr, n) {
// sorting the array
arr.sort((a, b) => a - b);
// Initialising the variable
// to store the sum
let sum = 0;
// Iterating through each element
// and adding it i times and
// subtracting it (n-1-i) times
for (let i = 0; i < n; i++) {
sum += i*arr[i] - (n-1-i)*arr[i];
}
return sum;
}
// Driver code
let arr = [16, 8, 9, 1, 15];
let n = arr.length;
console.log(sumPairs(arr, n));
// This code is contributed by phasing17
Time Complexity: O(n*log(n))
Auxiliary space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read