Rearrange a string S1 such that another given string S2 is not its subsequence | Java program for the above approach ; 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
import java . util . * ; class GFG { static void rearrangeString ( char [ ] s1 , char [ ] s2 ) { int [ ] cnt = new int [ 26 ] ; for ( int i = 0 ; i < s2 . length ; i ++ ) cnt [ s2 [ i ] - ' a ' ] ++ ; int unique = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) if ( cnt [ i ] != 0 ) unique ++ ; if ( unique == 1 ) { int count_in_s2 = s2 . length ; int count_in_s1 = 0 ; for ( int i = 0 ; i < s1 . length ; i ++ ) if ( s1 [ i ] == s2 [ 0 ] ) count_in_s1 ++ ; if ( count_in_s1 < count_in_s2 ) { System . out . print ( new String ( s1 ) ) ; return ; } System . out . print ( - 1 ) ; } else { int inc = 1 ; for ( int i = 0 ; i < s2 . length - 1 ; i ++ ) if ( s2 [ i ] > s2 [ i + 1 ] ) inc = 0 ; if ( inc == 1 ) { Arrays . sort ( s1 ) ; for ( int k = 0 ; k < s1 . length / 2 ; k ++ ) { char temp = s1 [ k ] ; s1 [ k ] = s1 [ s1 . length - k - 1 ] ; s1 [ s1 . length - k - 1 ] = temp ; } System . out . print ( new String ( s1 ) ) ; } else { Arrays . sort ( s1 ) ; System . out . print ( new String ( s1 ) ) ; } } } public static void main ( String [ ] args ) { char [ ] s1 = " abcd " . toCharArray ( ) ; char [ ] s2 = " ab " . toCharArray ( ) ; rearrangeString ( s1 , s2 ) ; } }