Sum of absolute differences of indices of occurrences of each array element | Python3 program for the above approach ; Function to find sum of differences of indices of occurrences of each unique array element ; Stores indices of each array element ; Store the indices ; Stores the sums ; Traverse the array ; Find sum for each element ; Iterate over the Map ; Calculate sum of occurrences of arr [ i ] ; Store sum for current element ; Print answer for each element ; Driver code ; Given array ; Given size ; Function Call
from collections import defaultdict NEW_LINE def sum_i ( arr , n ) : NEW_LINE INDENT mp = defaultdict ( lambda : [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] . append ( i ) NEW_LINE DEDENT ans = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for it in mp [ arr [ i ] ] : NEW_LINE INDENT sum += abs ( it - i ) NEW_LINE ans [ i ] = sum NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 1 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE sum_i ( arr , n ) NEW_LINE DEDENT