![]() |
VOOZH | about |
Two strings are given, we need to find whether we can form second string by swapping the character of the first string.
Examples:
Input : str1 = "geeksforgeeks" str2 = "geegeeksksfor" Output : YES Input : str1 = "geeksfor" str2 = "geeekfor" Output : NO
First of all, we will find the length of strings and if lengths are not equal that means we can not form the target string by swapping characters of the first string. If lengths are equal then we iterate through the first string and create a map for it and after that, we will iterate through the second string and decrease the count of the map if any of the indexes go negative in the map that means we can not form the target string otherwise we can form the target string.
Algorithm:
1- l1 = str1.length() && l2 = str2.length()
2- if (l1 != l2)
print "NO"
3- Else
map[26] = {0};
for i=0 to l1
map[str1[i]-'a']++;
for i=0 to l2
map[str2[i]-'a']--;
if (map[str[2]-'a'<0)
print "NO"
4- if no index goes negative print "YES"
5- End
Implementation:
YES
Time Complexity: O(n)
Auxiliary Space: O(1)