text: Check if a string can be transformed to another by sorting substrings | Function to check if str1 can be transformed to t by sorting substrings ; Occur [ i ] stores the indices of char ( ' a ' + i ) in string s ; idx [ i ] stores the next available index of char ( ' a ' + i ) in occur [ i ] ; If this char is not available anymore ; Conversion not possible ; If one of the smaller characters is available and occurs before ; Conversion not possible ; Print the answer ; Driver Code
code: function canTransform ( s , t ) { var n = s . length ; var occur = Array . from ( Array ( 26 ) , ( ) => new Array ( ) ) ; for ( var x = 0 ; x < n ; x ++ ) { var ch = s [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; occur [ ch ] . push ( x ) ; } var idx = Array ( 26 ) . fill ( 0 ) ; var poss = true ; for ( var x = 0 ; x < n ; x ++ ) { var ch = t [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; if ( idx [ ch ] >= occur [ ch ] . length ) { poss = false ; break ; } for ( var small = 0 ; small < ch ; small ++ ) { if ( idx [ small ] < occur [ small ] . length && occur [ small ] [ idx [ small ] ] < occur [ ch ] [ idx [ ch ] ] ) { poss = false ; break ; } } idx [ ch ] ++ ; } if ( poss ) { document . write ( " " ) ; } else { document . write ( " " ) ; } } var s , t ; s = " " ; t = " " ; canTransform ( s , t ) ;