Minimum swaps required between two strings to make one string strictly greater than the other
Input: A = “1432”, B = “789”, M = 4, N = 3
One possible way is to swap characters at index 0 of both the strings. Therefore, A modifies to “7432” and B modifies to “189”.
Input: A = “3733”, B = “3333”, M = 4, N = 4
Step 1:Swap character at index 1 of string A with character at index 0 of string B. The strings A and B are modified to “3333” and “7333”.
Step 2: Swap the character at index 0 of string A with a character at index 0 of string B. The strings A and B are modified to “7333” and “3333”.
Approach: It can be observed that if M ≤ N and all the characters are the same, including both strings, then it is not possible to make string A strictly greater than string B. Otherwise, string A can be made strictly greater than string B by placing the two different characters at the 0th index of both strings in a maximum of two moves.
Follow the steps below to solve the problem:
- First, check if the first character of string A is greater than the first character of string B then print 0.
- Otherwise, check if B > A then 1 swap is needed, so swap A with B and print 1.
- Otherwise, check if all the characters are the same in both strings and M ≤ N then it is not possible, so print -1.
- Otherwise, check if there lies any character in A which is smaller than A or a character in B which is greater than B then print 1.
- Otherwise, check if there exists any character in A which is less than A or any character in B which is greater than B then print 2.
- Otherwise, return 0 if none of the above conditions satisfies.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.