Check whether two strings are isomorphic to each other in Python

In this article, we will learn how to check whether the given two strings are isomorphic to each other in Python. Two strings are isomorphic if there is one-to-one mapping possible for every character in string 1 to every character in string2.


Input: string1 = "aaabb"
       string2 = "xxxyy"
Output: True
Explanation: character a to character x and character b maps to character y.

Input: string1 = "aaabb"
       string2 = "zxcvb"
Output: False

Check whether two strings are isomorphic in Python

1. Firstly, check if the length of two strings is equal if not return False.

2. Create a list mark of size 256 to store mark the visited characters in string2, initialize its value to Fasleand a list map to store the mapping of every character from string1 to string 2, initialize its value to -1.

3. Now iterate the string1 from range 0 to length of string

  • Check if the current character of string1 appears for the first time in it.
  • If the current character of the string2 already appeared, then return False.
  • Else, mark the current character of string2 visited and store the mapping of the current character in the map list.
  • Now check if the current character in string1 has already appeared, then check if the previous appearance mapped to the same character of the string, if not return False.

def stringIsomorphic(string1, string2): 
  m = len(string1) 
  n = len(string2) 

  if m != n: 
    return False
  mark = [False] * MAX_CHARS 
  map = [-1] * MAX_CHARS 

  for i in range(n): 
    if map[ord(string1[i])] == -1: 
      if mark[ord(string2[i])] == True: 
        return False

      mark[ord(string2[i])] = True
      map[ord(string1[i])] = string2[i] 
    elif map[ord(string1[i])] != string2[i]: 
      return False

  return True

string1 = input("Enter the string 1: ")
string2 = input("Enter the string 2: ")
print(stringIsomorphic(string1, string2))


Enter the string 1: ccddaa
Enter the string 2: xxyyzz

Enter the string 1: abba
Enter the string 2: asdd

Also read: Python string startswith() Method

Leave a Reply

Your email address will not be published. Required fields are marked *