VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-one-string-can-be-converted-to-another/

⇱ Check if one string can be converted to another - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if one string can be converted to another

Last Updated : 12 Jul, 2025

Given two strings str and str1, the task is to check whether one string can be converted to other by using the following operation: 
 

  • Convert all the presence of a character by a different character.


For example, if str = "abacd" and operation is to change character 'a' to 'k', then the resultant str = "kbkcd"
Examples: 
 

Input: str = "abbcaa"; str1 = "bccdbb" 
Output: Yes 
Explanation: The mappings of the characters are: 
c --> d 
b --> c 
a --> b
Input: str = "abbc"; str1 = "bcca" 
Output: No 
Explanation: The mapping of characters are: 
a --> b 
b --> c 
c --> a 
Here, due to the presence of a cycle, a specific order cannot be found. 
 


 


Approach: 
 

  • According to the given operation, every unique character should map to a unique character may be same or different.
  • This can easily be checked by a Hashmap.
  • However, this fails in cases where there is a cycle in mapping and a specific order cannot be determined.
  • One example of such case is Example 2 above.
  • Therefore, for mapping, the first and final characters are stored as edges in a hashmap.
  • For finding cycle with the edges, these edges are mapped one by one to a parent and are checked for cycle using Union and Find Algorithm.


Below is the implementation of the above approach. 
 


Output: 
Yes

 

Time Complexity: O(N * logN), where N is the length of string s1.
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: