You have been given two strings, 'str1' and 'str2'.
Your task is to return true if the given two strings are isomorphic to each other, else return false.
Two strings are isomorphic if a one-to-one mapping is possible for every character of the first string ‘str1’ to every character of the second string ‘str2’ while preserving the order of the characters.
All occurrences of every character in the first string ‘str1’ should map to the same character in the second string, ‘str2’.
For example :
If str1 = “aab” and str2 = “xxy” then the output will be 1. ‘a’ maps to ‘x’ and ‘b’ maps to ‘y’.
If str1 = “aab” and str2 = “xyz” then the output will be 0. There are two different characters in 'str1', while there are three different characters in 'str2'. So there won't be one to one mapping between 'str1' and 'str2'.
The first line contains the strings 'str1' and the next line contains the string 'str2'.
Output format :
Print 1 if the two strings are isomorphic, else print 0.
aab
xxy
1
The character ‘a’ maps to ‘x’ and ‘b’ maps to ‘y’. Hence, the answer is 1 in this case.
aab
xyz
0
1 <= |str1|, |str2| <= 10^3
|str1| is the length of the string str1, and |str2| is the length of the string str2.
Can you solve this in O(N) time?
Think about mapping every character of str1 to str2.
The basic idea is to iterate through all the characters of str2 for every character of str1.
The steps are as follows:
O(N^2), where ‘N’ is the length of the strings.
Since we are traversing through the string “str1” for each character of “str1”, the overall time complexity will be O(N^2).
O(1).
Constant extra space is required. Hence, the overall space complexity is O(1).