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.
Input: A = “AGAIN”, B = “ACTION”
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”
- 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.