Minimize swaps of pairs of characters required such that no two adjacent characters in the string are same | javascript program for the above approach ; Function to check if S contains any pair of adjacent characters that are same ; Traverse the String S ; If current pair of adjacent characters are the same ; Return true ; Utility function to find the minimum number of swaps of pair of characters required to make all pairs of adjacent characters different ; Check if the required String is formed already ; Traverse the String S ; Swap the characters at i and j position ; Swap for Backtracking Step ; Function to find the minimum number of swaps of pair of characters required to make all pairs of adjacent characters different ; Stores the resultant minimum number of swaps required ; Function call to find the minimum swaps required ; Prvar the result ; Driver Code
var ansSwaps ; function check ( S ) { for ( var i = 1 ; i < S . length ; i ++ ) { if ( S [ i - 1 ] == S [ i ] ) { return false ; } } return true ; } function minimumSwaps ( S , swaps , idx ) { if ( check ( S ) ) { ansSwaps = Math . min ( ansSwaps , swaps ) ; } for ( var i = idx ; i < S . length ; i ++ ) { for ( var j = i + 1 ; j < S . length ; j ++ ) { swap ( S , i , j ) ; minimumSwaps ( S , swaps + 1 , i + 1 ) ; S = swap ( S , i , j ) ; } } } function swap ( arr , i , j ) { var temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } function findMinimumSwaps ( S ) { ansSwaps = Number . MAX_VALUE ; minimumSwaps ( S , 0 , 0 ) ; if ( ansSwaps == Number . MAX_VALUE ) document . write ( " " ) ; else document . write ( ansSwaps ) ; } var S = " " ; findMinimumSwaps ( S . split ( ' ' ) ) ;