Check whether two strings can be made equal by reversing substring of equal length from both strings | function to count inversion count of the string ; For storing frequency ; Add all the characters which are less than the ith character before i . ; Adding the count to inversion count ; Updating the character in the frequency array ; Function to check whether any of the string have a repeated character ; Function to check whether the string S1 and S2 can be made equal by reversing sub strings of same size in both strings ; Frequency array to check whether both string have same character or not ; Adding the frequency ; ; If the character is not in S1 ; Decrementing the frequency ; If both string doesnot have same characters or not ; Finding inversion count of both strings ; If inversion count is same , or have same parity or if any of the string have a repeated character then the answer is Yes else No ; Driver code
function inversionCount ( s ) { var freq = Array ( 26 ) . fill ( 0 ) ; var inv = 0 ; for ( var i = 0 ; i < s . length ; i ++ ) { var temp = 0 ; for ( var j = 0 ; j < String . fromCharCode ( s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ; j ++ ) temp += freq [ j ] ; inv += ( i - temp ) ; freq [ s [ i ] - ' ' ] ++ ; } return inv ; } function haveRepeated ( S1 , S2 ) { var freq = Array ( 26 ) . fill ( 0 ) ; S1 . forEach ( i => { if ( freq [ i - ' ' ] > 0 ) return true ; freq [ i - ' ' ] ++ ; } ) ; for ( var i = 0 ; i < 26 ; i ++ ) freq [ i ] = 0 ; S2 . split ( ' ' ) . forEach ( i => { if ( freq [ i - ' ' ] > 0 ) return true ; freq [ i - ' ' ] ++ ; } ) ; return false ; } function checkToMakeEqual ( S1 , S2 ) { var freq = Array ( 26 ) . fill ( 0 ) ; for ( var i = 0 ; i < S1 . length ; i ++ ) { freq [ S1 [ i ] - ' ' ] ++ ; } var flag = 0 ; for ( var i = 0 ; i < S2 . length ; i ++ ) { if ( freq [ S2 [ i ] - ' ' ] == 0 ) { flag = true ; break ; } freq [ S2 [ i ] - ' ' ] -- ; } if ( flag == true ) { document . write ( " " ) ; return ; } var invCount1 = inversionCount ( S1 ) ; var invCount2 = inversionCount ( S2 ) ; if ( invCount1 == invCount2 || ( invCount1 & 1 ) == ( invCount2 & 1 ) || haveRepeated ( S1 , S2 ) ) { document . write ( " " ) ; } else document . write ( " " ) ; } var S1 = " " , S2 = " " ; checkToMakeEqual ( S1 , S2 ) ;