File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Python3 program for the above approach
2+ from collections import defaultdict
3+
4+ # Function to find sum of differences
5+ # of indices of occurrences of each
6+ # unique array element
7+ def sum_i (arr , n ):
8+ # Stores indices of each array element
9+ mp = defaultdict (lambda : [])
10+ # Store the indices
11+ for i in range (n ):
12+ mp [arr [i ]].append (i )
13+ # Stores the sums
14+ ans = [0 ] * n
15+
16+ # Traverse the array
17+ for i in range (n ):
18+ # Find sum for each element
19+ sum = 0
20+ # Iterate over the Map
21+ for it in mp [arr [i ]]:
22+ # Calculate sum of occurrences of arr[i]
23+ sum += abs (it - i )
24+ # Store sum for current element
25+ ans [i ] = sum
26+ # Print answer for each element
27+ for i in range (n ):
28+ print (ans [i ], end = " " )
29+
30+ # Driver code
31+ if __name__ == '__main__' :
32+ # Given array
33+ arr = [ 1 , 3 , 1 , 1 , 2 ]
34+ # Given size
35+ n = len (arr )
36+ # Function Call
37+ sum_i (arr , n )
38+ # This code is contributed by Shivam Singh
You can’t perform that action at this time.
0 commit comments