Minimum adjacent swaps to group similar characters together | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( string S , int n ) { int swaps = 0 ; vector < vector < int > > arr ( 26 ) ; for ( int i = 0 ; i < n ; i ++ ) { int pos = S [ i ] - ' a ' ; arr [ pos ] . push_back ( i ) ; } for ( char ch = ' a ' ; ch <= ' z ' ; ++ ch ) { int pos = ch - ' a ' ; for ( int i = 1 ; i < arr [ pos ] . size ( ) ; ++ i ) { swaps += abs ( arr [ pos ] [ i ] - arr [ pos ] [ i - 1 ] - 1 ) ; } } return swaps ; } int main ( ) { string S = " abbccabbcc " ; int N = S . length ( ) ; cout << minSwaps ( S , N ) ; return 0 ; }