Lexicographically smaller string by swapping at most one character pair | 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
function swap ( str , i , j ) { let tempArr = str . split ( " " ) ; let temp = tempArr [ i ] ; tempArr [ i ] = tempArr [ j ] ; tempArr [ j ] = temp ; return ( tempArr ) . join ( " " ) ; } function IsLexicographicallySmaller ( A , B ) { if ( A < ( B ) ) { return true ; } let temp = A ; let p = temp . split ( " " ) ; p . sort ( ) ; temp = ( p ) . join ( " " ) ; let index = - 1 ; for ( let i = 0 ; i < A . length ; i ++ ) { if ( A [ i ] != temp [ i ] ) { index = i ; break ; } } if ( index == - 1 ) { return false ; } let j = 0 ; for ( let i = 0 ; i < A . length ; i ++ ) { if ( A [ i ] == temp [ index ] ) j = i ; } A = swap ( A , index , j ) ; if ( A < ( B ) ) { return true ; } else { return false ; } } let A = " " ; let B = " " ; if ( IsLexicographicallySmaller ( A , B ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }