Given two strings, determine whether they are isomorphic. Two strings, X and Y, are called isomorphic if all occurrences of each character in X can be replaced with another character to get Y and vice-versa.

For example, consider strings ACAB and XCXY. They are isomorphic as we can map 'A' —> 'X', 'B' —> 'Y' and 'C' —> 'C'.

 
Note that mapping from a character to itself is allowed, but the same character may not replace two characters.

Practice this problem

 
A naive solution would be to check if every character in the first string is mapped to the same character in the second string for all its occurrences. But even then, two characters in the first string might still be mapped to the same character in the second string. So, we have to repeat the process for the second string as well, i.e., check if every character in the second string is mapped to the same character in the first string for all its occurrences.

The time complexity of this solution is O(n2), where n is the length of each string. We can improve time complexity to linear by using O(n) space.

 
The idea is to use hashing. The following solution uses a map to store a mapping from characters of string X to string Y and a set to store already mapped characters of string Y; the rest of the code is pretty much straightforward:

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

ACAB and XCXY are Isomorphic

Java


Download  Run Code

Output:

ACAB and XCXY are Isomorphic

Python


Download  Run Code

Output:

ACAB and XCXY are Isomorphic