Array formed using sum of absolute differences of that element with all other elements
Given a sorted array arr[] of N distinct positive integers. The task is to generate an array such that the element at each index in the new array is the sum of absolute differences of the corresponding element with all other elements of the given array.
Input: arr[] = [2, 3, 5]
Output: [4, 3, 5]
Explanation:
distance(2) = |2 – 3| + |2 – 5| = 4
distance(3) = |3 – 2| + |3 – 5| = 3
distance(5) = |5 – 2| + |5 – 3| = 5
Therefore, we will return [4, 3, 5]
Input: arr[] = [2, 3, 5, 6]
Output: [8, 6, 6, 8]
Explanation:
distance(2) = |2 – 3| + |2 – 5| + |2 – 6|= 8
distance(3) = |3 – 2| + |3 – 5| + |3 – 6|= 6
distance(5) = |5 – 2| + |5 – 3| + |5 – 6|= 6
distance(6) = |6 – 2| + |6 – 3| + |6 – 5|= 8
Therefore, we will return [8, 6, 6, 8]
Naive Approach: The idea is to generate all possible pairs for each element in the array arr[] and add the summation of the absolute difference of the pairs for each element in the new array. Print the array after the above steps for all the elements.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > calculate( int * arr, int n)
{
vector< int > ans;
for ( int i = 0; i < n; i++)
{
int sum = 0;
for ( int j = 0; j < n; j++)
{
sum += abs (arr[i] - arr[j]);
}
ans.push_back(sum);
}
return ans;
}
int main()
{
int arr[] = { 2, 3, 5, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
vector< int > ans = calculate(arr, n);
cout << "[" ;
for ( auto itr : ans)
cout << itr << ", " ;
cout << "]" ;
return 0;
}
|
Java
import java.util.*;
class GFG {
private static List<Integer>
calculate( int [] arr)
{
int n = arr.length;
List<Integer> ans
= new ArrayList<Integer>();
for ( int i = 0 ;
i < arr.length; i++) {
int sum = 0 ;
for ( int j = 0 ;
j < arr.length; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
ans.add(sum);
}
return ans;
}
public static void
main(String[] args)
{
int [] arr = { 2 , 3 , 5 , 6 };
System.out.println(calculate(arr));
}
}
|
Python3
def calculate(arr):
n = len (arr)
ans = []
for i in range (n):
sum = 0
for j in range ( len (arr)):
sum + = abs (arr[i] - arr[j])
ans.append( sum )
return ans
if __name__ = = '__main__' :
arr = [ 2 , 3 , 5 , 6 ]
print (calculate(arr))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
private static List< int > calculate( int [] arr)
{
int n = arr.Length;
List< int > ans = new List< int >();
for ( int i = 0; i < arr.Length; i++)
{
int sum = 0;
for ( int j = 0; j < arr.Length; j++)
{
sum += Math.Abs(arr[i] - arr[j]);
}
ans.Add(sum);
}
return ans;
}
public static void Main( string [] args)
{
int [] arr = { 2, 3, 5, 6 };
List< int > tmp = calculate(arr);
Console.Write( "[" );
for ( int i = 0; i < tmp.Count; i++)
{
if (i != tmp.Count - 1)
{
Console.Write(tmp[i] + ", " );
}
else
{
Console.Write(tmp[i]);
}
}
Console.Write( "]" );
}
}
|
Javascript
<script>
function
calculate(arr)
{
let n = arr.length;
let ans
= [];
for (let i = 0;
i < arr.length; i++) {
let sum = 0;
for (let j = 0;
j < arr.length; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
ans.push(sum);
}
return ans;
}
let arr = [ 2, 3, 5, 6 ];
document.write(calculate(arr));
</script>
|
Time Complexity: O(N^2)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach the idea is to keep track of the accumulated subtraction of the values to the left and of the sum of values to the right. The sum of the difference of all the pairs for each element is given by:
num_of_elements_to_the_left * current_value -num_of_elements_to_the_right * current_value
- Find the sum of all the elements in the given array(say sum).
- Initialize sub as 0.
- Traverse the given array and for each element do the following:
- Subtract the current value arr[i] from the sum.
- Add the difference of all the pairs for each element using the formula to the resultant array:
sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum
- Subtract the current value arr[i] from the sum.
- Print the resultant array after the above steps.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > calculate( int arr[],
int n)
{
int sub = 0;
int sum = 0;
vector< int > ans;
for ( int i = n - 1;
i >= 0; i--)
sum += arr[i];
for ( int i = 0; i < n; i++)
{
sum -= arr[i];
ans.push_back(sub + (i * arr[i]) -
((n - i - 1) *
arr[i]) + sum);
sub -= arr[i];
}
return ans;
}
int main()
{
int arr[] = {2, 3, 5, 6};
int n = sizeof (arr) /
sizeof (arr[0]);
vector< int > ans = (calculate(arr, n));
for ( int i = 0; i < n; i++)
cout << ans[i] << " " ;
}
|
Java
import java.util.*;
class GFG {
private static List<Integer>
calculate( int [] arr)
{
int n = arr.length;
int sub = 0 ;
int sum = 0 ;
List<Integer> ans
= new ArrayList<Integer>();
for ( int i = n - 1 ; i >= 0 ; i--)
sum += arr[i];
for ( int i = 0 ; i < arr.length; i++) {
sum -= arr[i];
ans.add(sub
+ (i * arr[i])
- ((n - i - 1 )
* arr[i])
+ sum);
sub -= arr[i];
}
return ans;
}
public static void
main(String[] args)
{
int [] arr = { 2 , 3 , 5 , 6 };
System.out.println(calculate(arr));
}
}
|
Python3
def calculate (arr):
n = len (arr)
sub = 0
Sum = 0
ans = []
for i in range (n - 1 , - 1 , - 1 ):
Sum + = arr[i]
for i in range ( len (arr)):
Sum - = arr[i]
ans.append(sub + (i * arr[i]) -
((n - i - 1 ) * arr[i]) + Sum )
sub - = arr[i]
return ans
if __name__ = = '__main__' :
arr = [ 2 , 3 , 5 , 6 ]
print (calculate(arr))
|
C#
using System;
using System.Collections.Generic;
class GFG{
private static List< int > calculate( int [] arr)
{
int n = arr.Length;
int sub = 0;
int sum = 0;
List< int > ans = new List< int >();
for ( int i = n - 1; i >= 0; i--)
sum += arr[i];
for ( int i = 0; i < arr.Length; i++)
{
sum -= arr[i];
ans.Add(sub + (i * arr[i]) -
((n - i - 1) *
arr[i]) + sum);
sub -= arr[i];
}
return ans;
}
public static void Main(String[] args)
{
int [] arr = { 2, 3, 5, 6 };
Console.Write( "[ " );
foreach ( int i in calculate(arr))
Console.Write(i + ", " );
Console.Write( "]" );
}
}
|
Javascript
<script>
function calculate(arr, n)
{
var sub = 0;
var sum = 0;
var ans = [];
for ( var i = n - 1;
i >= 0; i--)
sum += arr[i];
for ( var i = 0; i < n; i++)
{
sum -= arr[i];
ans.push(sub + (i * arr[i]) -
((n - i - 1) *
arr[i]) + sum);
sub -= arr[i];
}
return ans;
}
var arr = [2, 3, 5, 6]
var n = arr.length;
var ans = (calculate(arr, n));
for ( var i = 0; i < n; i++)
document.write( ans[i] + " " );
</script>
|
Time Complexity: O(N)
Space Complexity: O(N)
Last Updated :
18 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...