Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in ‘str1’ map to same character in ‘str2’
Input: str1 = "aab", str2 = "xxy" Output: True 'a' is mapped to 'x' and 'b' is mapped to 'y'. Input: str1 = "aab", str2 = "xyz" Output: False One occurrence of 'a' in str1 has 'x' in str2 and other occurrence of 'a' has 'y'.
We strongly recommend that you click here and practice it, before moving on to the solution.
A Simple Solution is to consider every character of ‘str1’ and check if all occurrences of it map to same character in ‘str2’. Time complexity of this solution is O(n*n).
An Efficient Solution can solve this problem in O(n) time. The idea is to create an array to store mappings of processed characters.
1) If lengths of str1 and str2 are not same, return false. 2) Do following for every character in str1 and str2 a) If this character is seen first time in str1, then current of str2 must have not appeared before. (i) If current character of str2 is seen, return false. Mark current character of str2 as visited. (ii) Store mapping of current characters. b) Else check if previous occurrence of str1[i] mapped to same character.
Below is the implementation of above idea :
Thanks to Gaurav and Utkarsh for suggesting above approach.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.
- Meta Strings (Check if two strings can become same after a swap in one string)
- Check whether two strings can be made equal by reversing substring of equal length from both strings
- Check whether Strings are k distance apart or not
- Check if strings are rotations of each other or not | Set 2
- Program to check if two strings are same or not
- Check whether two strings are anagram of each other
- Check if two strings are k-anagrams or not
- Check if two strings are permutation of each other
- Check if there is any common character in two given strings
- Check if all the palindromic sub-strings are of odd length
- Check whether two strings contain same characters in same order
- Check if two strings have a common substring
- Check duplicates in a stream of strings
- Check whether two strings are anagrams of each other using unordered_map in C++
- Check whether two strings are equivalent or not according to given condition
- Check if two strings are same ignoring their cases
- Check if edit distance between two strings is one
- A Program to check if strings are rotations of each other or not
- Check whether an array of strings can correspond to a particular number X
- Check whether given string can be generated after concatenating given strings
Improved By : Sam007