Check if two given strings are isomorphic to each other in Python

Check if strings are isomorphic to Each Other in Python

Here on this page, we will learn how to Check if strings are isomorphic to Each Other in Python Programming Language.

Example :

  • Input :  String 1:- A B A C B A, String 2:- X P X Z P W
  • Output :  Not Isomorphic
  • Explanation : Two strings str1 and str2 are called isomorphic if a one-to-one mapping is possible for every character of str1 to every character of str2 while preserving the order.
Check if strings are isomorphic to Each Other in Python


The objective is to check if the two given strings, String1 and String2, are Isomorphic to each other or not. For two strings such as String1 and String2 to be Isomorphic, Each character of String1 must map to each character of String2 by altering the order of their occurrence.

For instance, In the adjacent figure, We have two examples. Let’s go through them one by one. The first example has String1 and String2 as “ABABA” and “XPXCPW” respectively. As we can see,  when we map the characters of String1 onto the characters on String2, we notice that the character “A” of String1 is mapping onto more than one character of String2 i.e both “X” and “W”. As the character “A” has more than once reference in String2, The two strings, String1 and String2, are not Isomorphic.

Similarly, In the second example, the strings, String1 and String2, are “ABABA” and “XPXCPX” respectively. Now when we map the characters of String1 onto String2, we can see that they all map perfectly. The characters “A”“B” and “C” of String1 map with the characters “X”“P” and “C” of String2. Therefore, String1 and String2 are Isomorphic.

Check if strings are isomorphic to Each Other

Python Code

def isisomorphic(str1, str2):
    if len(str1) != len(str2):
        return False
        map1, map2 = {}, {}
        for i in range(len(str1)):
            ch1, ch2 = str1[i], str2[i]
            if ch1 not in map1:
                map1[ch1] = ch2
            if ch2 not in map2:
                map2[ch2] = ch1
            if map1[ch1] != ch2 or map2[ch2] != ch1:
                return False
    return True

str1 = "abacba"
str2 = "xpxcpx"
print(isisomorphic(str1, str2))



For similar Questions click on given button.