Lexicographically smaller string by swapping at most one character pair | C # program check whether is it possible to make String A lexicographically smaller than String B ; Swap function ; Function that finds whether is it possible to make String A lexicographically smaller than String B ; Condition if String A is already smaller than B ; Sorting temp String ; Condition for first changed character of String A and temp ; Condition if String A is already sorted ; Finding first changed character from last of String A ; Swap the two characters ; Condition if String A is smaller than B ; Driver Code
using System ; class GFG { static string swap ( string str , int i , int j ) { char [ ] tempArr = str . ToCharArray ( ) ; char temp = tempArr [ i ] ; tempArr [ i ] = tempArr [ j ] ; tempArr [ j ] = temp ; return new string ( tempArr ) ; } static bool IsLexicographicallySmaller ( string A , string B ) { if ( A . CompareTo ( B ) < 0 ) { return true ; } string temp = A ; char [ ] p = temp . ToCharArray ( ) ; Array . Sort ( p ) ; temp = new string ( p ) ; int index = - 1 ; for ( int i = 0 ; i < A . Length ; i ++ ) { if ( A [ i ] != temp [ i ] ) { index = i ; break ; } } if ( index == - 1 ) { return false ; } int j = 0 ; for ( int i = 0 ; i < A . Length ; i ++ ) { if ( A [ i ] == temp [ index ] ) j = i ; } A = swap ( A , index , j ) ; if ( A . CompareTo ( B ) < 0 ) { return true ; } else { return false ; } } public static void Main ( string [ ] args ) { string A = " AGAIN " ; string B = " ACTION " ; if ( IsLexicographicallySmaller ( A , B ) ) { Console . Write ( " Yes " ) ; } else { Console . Write ( " No " ) ; } } }