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++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the new arrayvector<int> calculate(int* arr, int n){         // Initialize the Arraylist    vector<int> ans;Â
    // Sum of absolute differences    // of element with all elements    for(int i = 0; i < n; i++)    {                 // Initialize int sum to 0        int sum = 0;Â
        for(int j = 0; j < n; j++)        {            sum += abs(arr[i] - arr[j]);        }Â
        // Add the value of sum to ans        ans.push_back(sum);    }Â
    // Return the final ans    return ans;}Â
// Driver Codeint main(){         // Given array arr[]    int arr[] = { 2, 3, 5, 6 };    int n = sizeof(arr) / sizeof(arr[0]);         // Function call    vector<int> ans = calculate(arr, n);         cout << "[";    for(auto itr : ans)        cout << itr << ", ";             cout << "]";         return 0;}// This code is contributed by jrishabh99 |
Java
// Java program for the above approach import java.util.*; Â
class GFG { Â
    // Function to return the new array     private static List<Integer>     calculate(int[] arr)     {         // Length of the arraylist         int n = arr.length; Â
        // Initialize the Arraylist         List<Integer> ans             = new ArrayList<Integer>(); Â
        // Sum of absolute differences         // of element with all elements         for (int i = 0;             i < arr.length; i++) { Â
            // Initialize int sum to 0             int sum = 0; Â
            for (int j = 0;                 j < arr.length; j++) { Â
                sum += Math.abs(arr[i] - arr[j]);             } Â
            // Add the value of sum to ans             ans.add(sum);         } Â
        // Return the final ans         return ans;     } Â
    // Driver Code     public static void        main(String[] args)     {         // Given array arr[]         int[] arr = { 2, 3, 5, 6 }; Â
        // Function Call         System.out.println(calculate(arr));     } } |
Python3
# Python3 program for the above approach Â
# Function to return the new array # private static List<Integer> def calculate(arr): Â
    # Length of the arraylist     n = len(arr) Â
    # Initialize the Arraylist     ans = [] Â
    # Sum of absolute differences     # of element with all elements     for i in range(n): Â
        # Initialize sum to 0         sum = 0Â
        for j in range(len(arr)):             sum += abs(arr[i] - arr[j]) Â
        # Add the value of sum to ans         ans.append(sum) Â
    # Return the final ans     return ans Â
# Driver Code if __name__ == '__main__': Â
    # Given array arr[]     arr = [ 2, 3, 5, 6 ] Â
    # Function call     print(calculate(arr)) Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic;Â
class GFG{Â
// Function to return the new arrayprivate static List<int> calculate(int[] arr){         // Length of the arraylist    int n = arr.Length;Â
    // Initialize the Arraylist    List<int> ans = new List<int>();Â
    // Sum of absolute differences    // of element with all elements    for(int i = 0; i < arr.Length; i++)    {                 // Initialize int sum to 0        int sum = 0;Â
        for(int j = 0; j < arr.Length; j++)        {            sum += Math.Abs(arr[i] - arr[j]);        }Â
        // Add the value of sum to ans        ans.Add(sum);    }Â
    // Return the final ans    return ans;}Â
// Driver Codepublic static void Main(string[] args){Â Â Â Â Â Â Â Â Â // Given array arr[]Â Â Â Â 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("]");}}Â
// This code is contributed by rutvik_56 |
Javascript
<script>Â
// Javascript program for// the above approachÂ
   // Function to return the new array   function    calculate(arr)    {        // Length of the arraylist        let n = arr.length;          // Initialize the Arraylist        let ans            = [];          // Sum of absolute differences        // of element with all elements        for (let i = 0;            i < arr.length; i++) {              // Initialize let sum to 0            let sum = 0;              for (let j = 0;                j < arr.length; j++) {                  sum += Math.abs(arr[i] - arr[j]);            }              // Add the value of sum to ans            ans.push(sum);        }          // Return the final ans        return ans;    }     // Driver Code         // Given array arr[]       let arr = [ 2, 3, 5, 6 ];          // Function Call        document.write(calculate(arr));Â
</script> |
[8, 6, 6, 8]
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++
// C++ program for the // above approach#include <bits/stdc++.h>using namespace std;Â
// Function to return list of// total Distance of each element// from other elements in arrayvector<int> calculate(int arr[],                      int n){  int sub = 0;  int sum = 0;Â
  // Initialize the arraylist  vector<int> ans;Â
  // Keep track of the   // accumulated of the   // sum of values to right  for (int i = n - 1;           i >= 0; i--)    sum += arr[i];Â
  // Keep track of the   // accumulated subtraction   // of the values to the left  for (int i = 0; i < n; i++)   {    sum -= arr[i];Â
    // Add the value to the     // resultant array ans[]    ans.push_back(sub + (i * arr[i]) -                  ((n - i - 1) *                   arr[i]) + sum);Â
    sub -= arr[i];  }     // Return the final   // answer  return ans;}Â
// Driver Codeint main(){  // Initialize the array  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] << " ";}Â
// This code is contributed by Chitranayal |
Java
// Java program for the above approach import java.util.*; Â
class GFG { Â
    // Function to return list of     // total Distance of each element     // from other elements in array     private static List<Integer>     calculate(int[] arr)     {         // Length of the array         int n = arr.length;         int sub = 0;         int sum = 0; Â
        // Initialize the arraylist         List<Integer> ans             = new ArrayList<Integer>(); Â
        // Keep track of the accumulated         // of the sum of values to right         for (int i = n - 1; i >= 0; i--)             sum += arr[i]; Â
        // Keep track of the accumulated         // subtraction of the values to the left         for (int i = 0; i < arr.length; i++) { Â
            sum -= arr[i]; Â
            // Add the value to the resultant             // array ans[]             ans.add(sub                     + (i * arr[i])                     - ((n - i - 1)                     * arr[i])                     + sum); Â
            sub -= arr[i];         }         // return the final answer         return ans;     } Â
    // Driver Code     public static void        main(String[] args)     {         // Initialize the array         int[] arr = { 2, 3, 5, 6 }; Â
        // Function Call         System.out.println(calculate(arr));     } } |
Python3
# Python3 program for the above approach Â
# Function to return list of # total Distance of each element # from other elements in array def calculate (arr):Â
    # Length of the array    n = len(arr)    sub = 0    Sum = 0Â
    # Initialize the ArrayList    ans = []Â
    # Keep track of the accumulated    # of the sum of values to right    for i in range(n - 1, -1, -1):        Sum += arr[i]Â
    # Keep track of the accumulated    # subtraction of values to left    for i in range(len(arr)):        Sum -= arr[i]Â
        # Add the value to the resultant        # array ans[]        ans.append(sub + (i * arr[i]) -               ((n - i - 1) * arr[i]) + Sum)Â
        sub -= arr[i]Â
    # Return the final answer    return ansÂ
# Driver Codeif __name__ == '__main__':         # Initialize the array    arr = [ 2, 3, 5, 6 ]Â
    # Function call    print(calculate(arr))Â
# This code is contributed by himanshu77 |
C#
// C# program for the above approach using System;using System.Collections.Generic;Â
class GFG{ Â
// Function to return list of // total Distance of each element // from other elements in array private static List<int> calculate(int[] arr) {          // Length of the array     int n = arr.Length;     int sub = 0;     int sum = 0; Â
    // Initialize the arraylist     List<int> ans = new List<int>(); Â
    // Keep track of the accumulated     // of the sum of values to right     for(int i = n - 1; i >= 0; i--)         sum += arr[i]; Â
    // Keep track of the accumulated     // subtraction of the values to the left     for(int i = 0; i < arr.Length; i++)    {         sum -= arr[i]; Â
        // Add the value to the resultant         // array ans[]         ans.Add(sub + (i * arr[i]) -                  ((n - i - 1) *                  arr[i]) + sum); Â
        sub -= arr[i];     }         // return the readonly answer     return ans; } Â
// Driver Code public static void Main(String[] args) {          // Initialize the array     int[] arr = { 2, 3, 5, 6 }; Â
    // Function Call     Console.Write("[ ");     foreach(int i in calculate(arr))        Console.Write(i + ", ");             Console.Write("]"); } } Â
// This code is contributed by amal kumar choubey |
Javascript
<script>// Javascript program for the // above approachÂ
// Function to return list of// total Distance of each element// from other elements in arrayfunction calculate(arr, n){Â Â var sub = 0;Â Â var sum = 0;Â
  // Initialize the arraylist  var ans = [];Â
  // Keep track of the   // accumulated of the   // sum of values to right  for (var i = n - 1;           i >= 0; i--)    sum += arr[i];Â
  // Keep track of the   // accumulated subtraction   // of the values to the left  for (var i = 0; i < n; i++)   {    sum -= arr[i];Â
    // Add the value to the     // resultant array ans[]    ans.push(sub + (i * arr[i]) -                  ((n - i - 1) *                   arr[i]) + sum);Â
    sub -= arr[i];  }     // Return the final   // answer  return ans;}Â
// Driver Code// Initialize the arrayvar 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] + " ");Â
// This code is contributed by famously.</script> |
[8, 6, 6, 8]
Â
Time Complexity: O(N)
Space Complexity: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
