Given two strings A and B of all uppercase letters, the task is to find whether is it possible to make string A strictly lexicographically smaller than string B by swapping at most one pair of characters in A.
Examples: 
Input: A = “AGAIN”, B = “ACTION”
Output: Yes
Explanation:
We can make string A strictly lexicographically smaller than string B by swapping G and A (AAGIN)
AAGIN is lexicographically smaller than ACTION
Input: A = “APPLE” B = “AAAAAPPPLLE”
Output: No
Approach:
- Sort string A.
- We can find the first position where A and sorted(A) doesn’t match.
- We then find the letter that should be in that position and swap it with the letter in the sorted(A).
- If there are multiple choices, it is better to take the one that occurs last, since it makes the resulting string smallest.
- Now, compare string A and string B.
Below is the implementation of the above approach.
C++
| // C++ program check whether is// it possible to make string A// lexicographically smaller than string B#include <bits/stdc++.h>usingnamespacestd;// Swap functionvoidswap(char& x, char& y){    chartemp = x;    x = y;    y = temp;}// Function that finds whether is// it possible to make string A// lexicographically smaller than string BboolIsLexicographicallySmaller(    string A, string B){    // Condition if string A    // is already smaller than B    if(A < B) {        returntrue;    }    string temp = A;    // Sorting temp string    sort(temp.begin(), temp.end());    intindex = -1;    for(inti = 0; i < A.length(); i++) {        // Condition for first changed        // character of string A and temp        if(A[i] != temp[i]) {            index = i;            break;        }    }    // Condition if string A    // is already  sorted    if(index == -1) {        returnfalse;    }    intj;    // Finding first changed character    // from  last of string A    for(inti = 0; i < A.length(); i++) {        if(A[i] == temp[index])            j = i;    }    // Swap the two characters    swap(A[index], A[j]);    // Condition if string A    // is smaller   than B    if(A < B) {        returntrue;    }    else{        returnfalse;    }}// Driver Codeintmain(){    string A = "AGAIN";    string B = "ACTION";    if(IsLexicographicallySmaller(A, B)) {        cout << "Yes"             << "\n";    }    else{        cout << "No"             << "\n";    }    return0;} | 
Java
| // Java program check whether is// it possible to make String A// lexicographically smaller than String Bimportjava.util.*;classGFG{            // Swap function    staticString swap(String str, inti, intj)    {        char[] tempArr = str.toCharArray();        chartemp = tempArr[i];        tempArr[i] = tempArr[j];        tempArr[j] = temp;        returnString.valueOf(tempArr);    }        // Function that finds whether is    // it possible to make String A    // lexicographically smaller than String B    staticbooleanIsLexicographicallySmaller(String A, String B)    {        // Condition if String A        // is already smaller than B        if(A.compareTo(B) < 0) {            returntrue;        }        String temp = A;        charp[] = temp.toCharArray();        // Sorting temp String        Arrays.sort(p);        temp=String.valueOf(p);        intindex = -1;            for(inti = 0; i < A.length(); i++) {            // Condition for first changed            // character of String A and temp            if(A.charAt(i) != temp.charAt(i)) {                index = i;                break;            }        }            // Condition if String A        // is already sorted        if(index == -1) {            returnfalse;        }            intj = 0;            // Finding first changed character        // from last of String A        for(inti = 0; i < A.length(); i++) {            if(A.charAt(i) == temp.charAt(index))                j = i;        }            // Swap the two characters        A = swap(A, index, j);            // Condition if String A        // is smaller than B        if(A.compareTo(B) < 0) {            returntrue;        }            else{            returnfalse;        }    }        // Driver Code    publicstaticvoidmain(String args[])    {        String A = "AGAIN";        String B = "ACTION";            if(IsLexicographicallySmaller(A, B)) {            System.out.println("Yes");        }        else{            System.out.println("No");        }        }}// This code is contributed by AbhiThakur | 
Python3
| # Python3 program check # it possible to make string# A lexicographically smaller # than string B# Function that finds whether is# it possible to make string A# lexicographically smaller than # string BdefIsLexicographicallySmaller(A, B):    # Condition if string A    # is already smaller     # than B    if(A < B):        returnTrue    temp =A    # Sorting temp string    temp =''.join(sorted(temp))    index =-1    fori inrange(len(A)):        # Condition for first         # changed character of         # string A and temp        if(A[i] !=temp[i]):            index =i            break    # Condition if string A    # is already  sorted    if(index ==-1):        returnFalse          j =0    # Finding first changed    # character from last     # of string A    fori inrange(len(A)):        if(A[i] ==temp[index]):            j =i                A =list(A)    # Swap the two characters    A[index], A[j] =A[j], A[index]    A =''.join(A)    # Condition if string A    # is smaller than B    if(A < B):        returnTrue    else:        returnFalse# Driver CodeA ="AGAIN"B ="ACTION"if(IsLexicographicallySmaller(A, B)):    print("Yes")else:    print("No")# This code is contributed by avanitrachhadiya2155 | 
C#
| // C# program check whether is// it possible to make String A// lexicographically smaller // than String BusingSystem;classGFG{     // Swap functionstaticstringswap(stringstr,                    inti, intj){  char[] tempArr = str.ToCharArray();  chartemp = tempArr[i];  tempArr[i] = tempArr[j];  tempArr[j] = temp;  returnnewstring(tempArr);}     // Function that finds whether is// it possible to make String A// lexicographically smaller than String BstaticboolIsLexicographicallySmaller(stringA,                                        stringB){  // Condition if String A  // is already smaller than B  if(A.CompareTo(B) < 0)   {    returntrue;  }  stringtemp = A;  char[]p = temp.ToCharArray();  // Sorting temp String  Array.Sort(p);  temp=newstring(p);  intindex = -1;  for(inti = 0; i < A.Length; i++)   {    // Condition for first changed    // character of String A and temp    if(A[i] != temp[i])     {      index = i;      break;    }  }  // Condition if String A  // is already sorted  if(index == -1)   {    returnfalse;  }  intj = 0;  // Finding first changed character  // from last of String A  for(inti = 0; i < A.Length; i++)  {    if(A[i] == temp[index])      j = i;  }  // Swap the two characters  A = swap(A, index, j);  // Condition if String A  // is smaller than B  if(A.CompareTo(B) < 0)   {    returntrue;  }  else  {    returnfalse;  }}     // Driver CodepublicstaticvoidMain(string[]args){  stringA = "AGAIN";  stringB = "ACTION";  if(IsLexicographicallySmaller(A, B))   {    Console.Write("Yes");  }  else  {    Console.Write("No");  }}}// This code is contributed by Rutvik_56 | 
Javascript
| <script>// Javascript program check whether is// it possible to make String A// lexicographically smaller than String B // Swap functionfunctionswap(str,i,j){    let tempArr = str.split("");        let temp = tempArr[i];        tempArr[i] = tempArr[j];        tempArr[j] = temp;        return(tempArr).join("");}// Function that finds whether is    // it possible to make String A    // lexicographically smaller than String BfunctionIsLexicographicallySmaller(A, B){    // Condition if String A        // is already smaller than B        if(A < (B) ) {            returntrue;        }        let temp = A;        let p = temp.split("");         // Sorting temp String        p.sort();        temp=(p).join("");        let index = -1;             for(let i = 0; i < A.length; i++) {             // Condition for first changed            // character of String A and temp            if(A[i] != temp[i]) {                index = i;                break;            }        }             // Condition if String A        // is already sorted        if(index == -1) {            returnfalse;        }             let j = 0;             // Finding first changed character        // from last of String A        for(let i = 0; i < A.length; i++) {            if(A[i] == temp[index])                j = i;        }             // Swap the two characters        A = swap(A, index, j);             // Condition if String A        // is smaller than B        if(A < (B) ) {            returntrue;        }             else{            returnfalse;        }}// Driver Codelet A = "AGAIN";let B = "ACTION";if(IsLexicographicallySmaller(A, B)) {    document.write("Yes");}else{    document.write("No");}// This code is contributed by ab2127</script> | 
Yes
Time Complexity: O(N log N), for sorting the given string.
Auxiliary Space: O(N), for storing the given string in extra variable temp.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







