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 ; Given String ; Size of String ; Function Call
function minSwaps ( S , n ) { let swaps = 0 ; let arr = new Array ( 26 ) ; for ( let i = 0 ; i < arr . length ; i ++ ) arr [ i ] = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { let pos = S [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; arr [ pos ] . push ( i ) ; } for ( let ch = ' ' . charCodeAt ( 0 ) ; ch <= ' ' . charCodeAt ( 0 ) ; ++ ch ) { let pos = ch - ' ' . charCodeAt ( 0 ) ; for ( let i = 1 ; i < arr [ pos ] . length ; ++ i ) { swaps += Math . abs ( arr [ pos ] [ i ] - arr [ pos ] [ i - 1 ] - 1 ) ; } } return swaps ; } let S = " " ; let N = S . length ; document . write ( minSwaps ( S , N ) ) ;