Sum of absolute differences of indices of occurrences of each array element | Set 2 | Stores the count of occurrences and previous index of every element ; Constructor ; Function to calculate the sum of absolute differences of indices of occurrences of array element ; Stores the count of elements and their previous indices ; Initialize 2 arrays left [ ] and right [ ] of size N ; Traverse the given array ; If arr [ i ] is present in the Map ; Update left [ i ] to 0 and update the value of arr [ i ] in map ; Otherwise , get the value from the map and update left [ i ] ; Clear the map to calculate right [ ] array ; Traverse the array arr [ ] in reverse ; If arr [ i ] is present in theMap ; Update right [ i ] to 0 and update the value of arr [ i ] in the Map ; Otherwise get the value from the map and update right [ i ] ; Iterate in the range [ 0 , N - 1 ] and print the sum of left [ i ] and right [ i ] as the result ; Driver Code
class pair { constructor ( count , prevIndex ) { this . count = count ; this . prevIndex = prevIndex ; } } function findSum ( arr , n ) { let map = new Map ( ) ; let left = new Array ( n ) ; let right = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( ! map . has ( arr [ i ] ) ) { left [ i ] = 0 ; map . set ( arr [ i ] , new pair ( 1 , i ) ) ; } else { let tmp = map . get ( arr [ i ] ) ; left [ i ] = ( tmp . count ) * ( i - tmp . prevIndex ) + left [ tmp . prevIndex ] ; map . set ( arr [ i ] , new pair ( tmp . count + 1 , i ) ) ; } } map . clear ( ) ; for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( ! map . has ( arr [ i ] ) ) { right [ i ] = 0 ; map . set ( arr [ i ] , new pair ( 1 , i ) ) ; } else { let tmp = map . get ( arr [ i ] ) ; right [ i ] = ( tmp . count ) * ( Math . abs ( i - tmp . prevIndex ) ) + right [ tmp . prevIndex ] ; map . set ( arr [ i ] , new pair ( tmp . count + 1 , i ) ) ; } } for ( let i = 0 ; i < n ; i ++ ) document . write ( left [ i ] + right [ i ] + " " ) ; } let arr = [ 1 , 3 , 1 , 1 , 2 ] ; let N = arr . length ; findSum ( arr , N ) ;