Minimum adjacent swaps to group similar characters together | Function to find minimum adjacent swaps required to make all the same character adjacent ; Initialize answer ; Create a 2D array of size 26 ; Traverse the string ; Get character ; Append the current index in the corresponding vector ; Traverse each character from a to z ; Add difference of adjacent index ; Return answer ; Driver Code ; Given string ; Size of string ; Function Call
def minSwaps ( S , n ) : NEW_LINE INDENT swaps = 0 NEW_LINE arr = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT pos = ord ( S [ i ] ) - ord ( ' a ' ) NEW_LINE arr [ pos ] . append ( i ) NEW_LINE DEDENT for ch in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT pos = ch - ord ( ' a ' ) NEW_LINE for i in range ( 1 , len ( arr [ pos ] ) ) : NEW_LINE INDENT swaps += abs ( arr [ pos ] [ i ] - arr [ pos ] [ i - 1 ] - 1 ) NEW_LINE DEDENT DEDENT return swaps NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abbccabbcc " NEW_LINE N = len ( S ) NEW_LINE print ( minSwaps ( S , N ) ) NEW_LINE DEDENT