Sum of Manhattan distances between repetitions in a String | Function to find the sum of the manhattan distances between same characters in string ; Vector to store indices for each unique character of the string ; Append the position of each character in their respective vectors ; Store the required result ; Iterate over all the characters ; Calculate sum of all elements present in the vector ; Traverse the current vector ; Find suffix [ i + 1 ] ; Adding distance of all pairs whose first element is i and second element belongs to [ i + 1 , n ] ; Prthe result ; Driver Code ; Given Input ; Function Call
def SumofDistances ( s ) : NEW_LINE INDENT v = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( len ( v [ i ] ) ) : NEW_LINE INDENT sum += v [ i ] [ j ] NEW_LINE DEDENT for j in range ( len ( v [ i ] ) ) : NEW_LINE INDENT sum -= v [ i ] [ j ] NEW_LINE ans += ( sum - ( len ( v [ i ] ) - 1 - j ) * ( v [ i ] [ j ] ) ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " ababa " NEW_LINE SumofDistances ( s ) NEW_LINE DEDENT