Sum of absolute differences of indices of occurrences of each array element | 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 ; Given array ; Given size ; Function call
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 ) ;