Minimum swaps required between two strings to make one string strictly greater than the other | Java program for above approach ; Function to find the minimum number of steps to make A > B ; If all character are same and M <= N ; If there lies any character in B which is greater than B [ 0 ] ; If there lies any character in A which is smaller than A [ 0 ] ; If there lies a character which is in A and greater than A [ 0 ] ; If there lies a character which is in B and less than B [ 0 ] ; Otherwise ; Driver function
import java . util . * ; import java . lang . * ; class GFG { static int minSteps ( StringBuilder A , StringBuilder B , int M , int N ) { if ( A . charAt ( 0 ) > B . charAt ( 0 ) ) return 0 ; if ( B . charAt ( 0 ) > A . charAt ( 0 ) ) { return 1 ; } if ( M <= N && A . charAt ( 0 ) == B . charAt ( 0 ) && count ( A , A . charAt ( 0 ) ) == M && count ( B , B . charAt ( 0 ) ) == N ) return - 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( B . charAt ( i ) > B . charAt ( 0 ) ) return 1 ; } for ( int i = 1 ; i < M ; i ++ ) { if ( A . charAt ( i ) < A . charAt ( 0 ) ) return 1 ; } for ( int i = 1 ; i < M ; i ++ ) { if ( A . charAt ( i ) > A . charAt ( 0 ) ) { swap ( A , i , B , 0 ) ; swap ( A , 0 , B , 0 ) ; return 2 ; } } for ( int i = 1 ; i < N ; i ++ ) { if ( B . charAt ( i ) < B . charAt ( 0 ) ) { swap ( A , 0 , B , i ) ; swap ( A , 0 , B , 0 ) ; return 2 ; } } return 0 ; } static int count ( StringBuilder a , char c ) { int count = 0 ; for ( int i = 0 ; i < a . length ( ) ; i ++ ) if ( a . charAt ( i ) == c ) count ++ ; return count ; } static void swap ( StringBuilder s1 , int index1 , StringBuilder s2 , int index2 ) { char c = s1 . charAt ( index1 ) ; s1 . setCharAt ( index1 , s2 . charAt ( index2 ) ) ; s2 . setCharAt ( index2 , c ) ; } public static void main ( String [ ] args ) { StringBuilder A = new StringBuilder ( " adsfd " ) ; StringBuilder B = new StringBuilder ( " dffff " ) ; int M = A . length ( ) ; int N = B . length ( ) ; System . out . println ( minSteps ( A , B , M , N ) ) ; } }