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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( char & x , char & y ) { char temp = x ; x = y ; y = temp ; } bool IsLexicographicallySmaller ( string A , string B ) { if ( A < B ) { return true ; } string temp = A ; sort ( temp . begin ( ) , temp . end ( ) ) ; 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 ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { if ( A [ i ] == temp [ index ] ) j = i ; } swap ( A [ index ] , A [ j ] ) ; if ( A < B ) { return true ; } else { return false ; } } int main ( ) { string A = " AGAIN " ; string B = " ACTION " ; if ( IsLexicographicallySmaller ( A , B ) ) { cout << " Yes " << " STRNEWLINE " ; } else { cout << " No " << " STRNEWLINE " ; } return 0 ; }