Given two strings str1 and str2, the task is to check if a string str1 can be converted to string str2 by performing the following operations any number of times:
- Swap any two characters of str1.
- Swap all the occurrences of a character of str1 to all occurrences of any other distinct character of str1.
Input: str1 = “xyyzzlll”, str2 = “yllzzxxx”
Swap all occurrences of str1 and str1 modifies str1 to “yxxzzlll”
Swap all occurrences of str1 and str1 modifies str1 to “yllzzxxx”
Since str1 and str2 are equal, therefore, the required output is True.
Input: str1 = “xyyzzavl”, str2 = “yllzzvac”
Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:
- Initialize two arrays, say hash1 and hash2 to store the frequency of each distinct element of str1 and str2 respectively.
- Initialize two sets, say st1 and st2 to store the distinct characters of str1 and str2.
- Traverse the string and store the frequency of each distinct character of str1 and str2.
- Sort hash1 and hash2 array.
- If st1 and st2 are not equal then print false.
- Traverse hash1 and hash2 array using variable i and check if the value of (hash1[i] != hash2[i]) is true or not. If found to be true then print False.
- Otherwise, print True.
Below is the implementation of the above approach:
Time Complexity: O(N + M + 256)
Auxiliary Space: O(256)
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.