VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-characters-of-one-string-can-be-swapped-to-form-other/

⇱ Check if characters of one string can be swapped to form other - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if characters of one string can be swapped to form other

Last Updated : 7 Oct, 2022

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:


Output
YES

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: