Rearrange a string S1 such that another given string S2 is not its subsequence | Function to rearrange characters in string S1 such that S2 is not a subsequence of it ; Store the frequencies of characters of string s2 ; Traverse the string s2 ; Update the frequency ; Find the number of unique characters in s2 ; Increment unique by 1 if the condition satisfies ; Check if the number of unique characters in string s2 is 1 ; Store the unique character frequency ; Store occurence of it in s1 ; Find count of that character in the string s1 ; Increment count by 1 if that unique character is same as current character ; If count count_in_s1 is less than count_in_s2 , then print s1 and return ; Otherwise , there is no possible arrangement ; Checks if any character in s2 is less than its next character ; Iterate the string , s2 ; If s [ i ] is greater than the s [ i + 1 ] ; Set inc to 0 ; If inc = 1 , print s1 in decreasing order ; Otherwise , print s1 in increasing order ; Driver code
function rearrangeString ( s1 , s2 ) { let cnt = new Array ( 26 ) ; cnt . fill ( 0 ) ; for ( let i = 0 ; i < s2 . length ; i ++ ) cnt [ s2 [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] ++ ; let unique = 0 ; for ( let i = 0 ; i < 26 ; i ++ ) if ( cnt [ i ] != 0 ) unique ++ ; if ( unique == 1 ) { let count_in_s2 = s2 . length ; let count_in_s1 = 0 ; for ( let i = 0 ; i < s1 . length ; i ++ ) if ( s1 [ i ] == s2 [ 0 ] ) count_in_s1 ++ ; if ( count_in_s1 < count_in_s2 ) { document . write ( s1 . join ( " " ) ) ; return ; } document . write ( - 1 ) ; } else { let inc = 1 ; for ( let i = 0 ; i < s2 . length - 1 ; i ++ ) if ( s2 [ i ] . charCodeAt ( ) > s2 [ i + 1 ] . charCodeAt ( ) ) inc = 0 ; if ( inc == 1 ) { s1 . sort ( ) ; s1 . reverse ( ) ; document . write ( s1 . join ( " " ) ) ; } else { s1 . sort ( ) ; document . write ( s1 . join ( " " ) ) ; } } } let s1 = " " . split ( ' ' ) ; let s2 = " " . split ( ' ' ) ; rearrangeString ( s1 , s2 ) ;