Sum of absolute differences of indices of occurrences of each array element
Given an array arr[] consisting of N integers, the task for each array element arr[i] is to print the sum of |i – j| for all possible indices j such that arr[i] = arr[j].
Examples:
Input: arr[] = {1, 3, 1, 1, 2}
Output: 5 0 3 4 0
Explanation:
For arr[0], sum = |0 – 0| + |0 – 2| + |0 – 3| = 5.
For arr[1], sum = |1 – 1| = 0.
For arr[2], sum = |2 – 0| + |2 – 2| + |2 – 3| = 3.
For arr[3], sum = |3 – 0| + |3 – 2| + |3 – 3| = 4.
For arr[4], sum = |4 – 4| = 0.
Therefore, the required output is 5 0 3 4 0.
Input: arr[] = {1, 1, 1}
Output: 3 2 3
Naive approach: The simplest approach is to traverse the given array and for each element arr[i] ( 0 ? i ? N ), traverse the array and check if arr[i] is same as arr[j] ( 0 ? j ? N ). If found to be true, add abs(i – j) to the sum print the sum obtained for each array element.
C++
#include <bits/stdc++.h>
using namespace std;
void sum( int arr[], int n)
{
for ( int i = 0; i < n; i++) {
int sum = 0;
for ( int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
sum += abs (i - j);
}
}
cout << sum << " " ;
}
}
int main()
{
int arr[] = { 1, 3, 1, 1, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
sum(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
public static void sum( int [] arr, int n) {
for ( int i = 0 ; i < n; i++) {
int sum = 0 ;
for ( int j = 0 ; j < n; j++) {
if (arr[i] == arr[j]) {
sum += Math.abs(i - j);
}
}
System.out.print(sum + " " );
}
}
public static void main(String[] args) {
int [] arr = { 1 , 3 , 1 , 1 , 2 };
int n = arr.length;
sum(arr, n);
}
}
|
Python3
def sum (arr, n):
for i in range (n):
s = 0
for j in range (n):
if arr[i] = = arr[j]:
s + = abs (i - j)
print (s, end = " " )
if __name__ = = '__main__' :
arr = [ 1 , 3 , 1 , 1 , 2 ]
n = len (arr)
sum (arr, n)
|
Javascript
function sum(arr, n) {
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = 0; j < n; j++) {
if (arr[i] === arr[j]) {
sum += Math.abs(i - j);
}
}
console.log(sum + " " );
}
}
( function main() {
let arr = [1, 3, 1, 1, 2];
let n = arr.length;
sum(arr, n);
})();
|
C#
using System;
public class GFG
{
public static void Sum( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
{
int sum = 0;
for ( int j = 0; j < n; j++)
{
if (arr[i] == arr[j])
{
sum += Math.Abs(i - j);
}
}
Console.Write(sum + " " );
}
}
public static void Main()
{
int [] arr = { 1, 3, 1, 1, 2 };
int n = arr.Length;
Sum(arr, n);
}
}
|
Time Complexity: O(N2) where N is the size of the given array.
Auxiliary Space: O(1)
Efficient Approach: The idea is to use Map data structure to optimize the above approach. Follow the steps below to solve the problem:
- Initialize a Map to store the vector of indices for repetitions of each unique element present in the array.
- Traverse the given array from i = 0 to N – 1 and for each array element arr[i], initialize the sum with 0 and traverse the vector map[arr[i]] which stores the indices of the occurrences of the element arr[i].
- For each value j present in the vector, increment the sum by abs(i – j).
- After traversing the vector, store the sum for the element at index i and print the sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void sum( int arr[], int n)
{
map< int , vector< int > > mp;
for ( int i = 0; i < n; i++) {
mp[arr[i]].push_back(i);
}
int ans[n];
for ( int i = 0; i < n; i++) {
int sum = 0;
for ( auto it : mp[arr[i]]) {
sum += abs (it - i);
}
ans[i] = sum;
}
for ( int i = 0; i < n; i++) {
cout << ans[i] << " " ;
}
return ;
}
int main()
{
int arr[] = { 1, 3, 1, 1, 2 };
int n = sizeof (arr)
/ sizeof (arr[0]);
sum(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void sum( int arr[], int n)
{
HashMap<Integer, Vector<Integer>> mp = new HashMap<>();
for ( int i = 0 ; i < n; i++)
{
Vector<Integer> v = new Vector<>();
v.add(i);
if (mp.containsKey(arr[i]))
v.addAll(mp.get(arr[i]));
mp.put(arr[i], v);
}
int []ans = new int [n];
for ( int i = 0 ; i < n; i++)
{
int sum = 0 ;
for ( int it : mp.get(arr[i]))
{
sum += Math.abs(it - i);
}
ans[i] = sum;
}
for ( int i = 0 ; i < n; i++)
{
System.out.print(ans[i] + " " );
}
return ;
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 , 1 , 1 , 2 };
int n = arr.length;
sum(arr, n);
}
}
|
Python3
from collections import defaultdict
def sum_i(arr, n):
mp = defaultdict( lambda : [])
for i in range (n):
mp[arr[i]].append(i)
ans = [ 0 ] * n
for i in range (n):
sum = 0
for it in mp[arr[i]]:
sum + = abs (it - i)
ans[i] = sum
for i in range (n):
print (ans[i], end = " " )
if __name__ = = '__main__' :
arr = [ 1 , 3 , 1 , 1 , 2 ]
n = len (arr)
sum_i(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void sum( int []arr, int n)
{
Dictionary< int ,
List< int >> mp = new Dictionary< int ,
List< int >>();
for ( int i = 0; i < n; i++)
{
List< int > v = new List< int >();
v.Add(i);
if (mp.ContainsKey(arr[i]))
v.AddRange(mp[arr[i]]);
mp[arr[i]]= v;
}
int []ans = new int [n];
for ( int i = 0; i < n; i++)
{
int sum = 0;
foreach ( int it in mp[arr[i]])
{
sum += Math.Abs(it - i);
}
ans[i] = sum;
}
for ( int i = 0; i < n; i++)
{
Console.Write(ans[i] + " " );
}
return ;
}
public static void Main(String[] args)
{
int []arr = { 1, 3, 1, 1, 2 };
int n = arr.Length;
sum(arr, n);
}
}
|
Javascript
<script>
function sum(arr, n)
{
var mp = new Map();
for ( var i = 0; i < n; i++) {
if (mp.has(arr[i]))
{
var tmp = mp.get(arr[i]);
tmp.push(i);
mp.set(arr[i], tmp);
}
else
{
mp.set(arr[i], [i]);
}
}
var ans = Array(n);
for ( var i = 0; i < n; i++) {
var sum = 0;
mp.get(arr[i]).forEach(it => {
sum += Math.abs(it - i);
});
ans[i] = sum;
}
for ( var i = 0; i < n; i++) {
document.write( ans[i] + " " );
}
return ;
}
var arr = [1, 3, 1, 1, 2];
var n = arr.length;
sum(arr, n);
</script>
|
Time Complexity: O(N * L) where N is the size of the given array and L is the maximum frequency of any array element.
Auxiliary Space: O(N)
Last Updated :
26 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...