Minimize replacements or swapping of same indexed characters required to make two given strings palindromic
- Replace any character of the strings to any other character([a – z]).
- Swap any two characters present at the same index in both the strings.
Input: str1 = “abbd”, str2 = “dbca”
Swapping (str1, str2) modifies strings str1 to “dbbd” and str2 to “abca”
Replacing str2 to ‘c’ modifies string str2 to “acca”.
Therefore, after above 2 operations, strings str1 and str2 become palindromic.
Input: str1 = “geeksforgeeks”, str2 = “geeksforgeeks”
Approach: Follow the steps below to solve the problem:
- Initialize two variables, say i = 0 and j = 0 to store the index of left pointer and right pointer of both the strings respectively.
- Initialize a variable, say cntOp to store the count of minimum operations required to make both the strings palindromic string.
- Traverse both the string and check the following conditions:
- If str1[i] == str1[j] and str2[i] != str2[j] then replace the value of str2[i] to str2[j] and increment the value of cntOp by 1.
- If str1[i] != str1[j] and str2[i] == str2[j] then replace the value of str1[i] to str1[j] and increment the value of cntOp by 1.
- If str1[i] != str1[j] and str2[i] != str2[j] then check the if the value of (str1[i] == str2[j] and str2[i] == str1[j]) equal to true or not. If found to be true then swap(str1[i], str2[j]) and increment the value of cntOp by 1.
- Otherwise, replace str1[i] to str1[j], str2[i] to str2[j] and increment the value of cntOp by 2.
- Finally, print the value of cntOp.
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.