Check if two non-duplicate strings can be made equal after at most two swaps in one string
Given two strings A and B consisting of unique lowercase letters, the task is to check if both these strings can be made equal by using at most two swaps. Print Yes if they can. Otherwise, print No.
Input: A=”abcd”, B=”badc”
First swap a and b, and then swap c and d, in string A.
Input: A=”abcd”, B=”cbda”
Approach: In this problem, string A can only be converted to string B if:
Case 1: If A is already equal to B.
Case 2: If the number of differences in both the strings is less than equal to 3 and both the strings contains same character. Then its always possible to create B from A.
Case 3: If the number of differences is 4 and all the swapping pairs in string A are same and opposite in string B.
Now to solve this problem, follow the below steps:
- First, check if both the strings are already equal or not. If they are, then print Yes.
- Also, check if the size of both the string are equal or not. If it isn’t then print No.
- Create a vector, say b and store the indexes of character in string B.
- Create two maps, stay mp1 and mp2 to store the frequency of characters in strings A and B respectively.
- Now, check if the number of differences is less than or equal to 3, and both the maps, mp1 and mp2 have the same entries. If yes, then both the string can be made equal. So, print Yes.
- Also, both the strings can be made equal if they have 4 differences, but if it is a pair of two mirrored mistakes. So, print Yes if the differences are mirrored in two pairs.
- Otherwise, print No in the end.
Below is the implementation of the above approach:
Time Complexity: O(N*log N)
Auxiliary Space: O(N)