Python - Check if two strings are isomorphic in nature

Two strings are isomorphic if there exists a one-to-one mapping between characters of both strings. This means each character in the first string can be replaced to get the second string, and no two characters map to the same character.

What are Isomorphic Strings?

Strings are isomorphic when:

  • They have the same length
  • Each character in string1 maps to exactly one character in string2
  • No two different characters in string1 map to the same character in string2

For example: "aab" and "xxy" are isomorphic (a?x, b?y), but "aab" and "xyz" are not (both 'a' characters must map to the same character).

Method 1: Using Character Mapping Arrays

This approach uses two arrays to track character mappings and whether characters have been used ?

MAX_CHARS = 256

def check_isomorphic(str_1, str_2):
    len_1 = len(str_1)
    len_2 = len(str_2)
    
    if len_1 != len_2:
        return False
    
    marked = [False] * MAX_CHARS
    char_map = [-1] * MAX_CHARS
    
    for i in range(len_2):
        if char_map[ord(str_1[i])] == -1:
            if marked[ord(str_2[i])] == True:
                return False
            
            marked[ord(str_2[i])] = True
            char_map[ord(str_1[i])] = str_2[i]
            
        elif char_map[ord(str_1[i])] != str_2[i]:
            return False
    
    return True

# Test the function
str_1 = 'aababa'
str_2 = 'xxyyxx'
print("The first string is:", str_1)
print("The second string is:", str_2)
print("Are 'aab' and 'xxy' isomorphic?", check_isomorphic("aab", "xxy"))
print("Are 'aab' and 'xyz' isomorphic?", check_isomorphic("aab", "xyz"))
The first string is: aababa
The second string is: xxyyxx
Are 'aab' and 'xxy' isomorphic? True
Are 'aab' and 'xyz' isomorphic? False

Method 2: Using Dictionary for Mapping

A simpler approach using Python dictionaries to track character mappings ?

def are_isomorphic(s1, s2):
    if len(s1) != len(s2):
        return False
    
    map1to2 = {}
    map2to1 = {}
    
    for i in range(len(s1)):
        char1, char2 = s1[i], s2[i]
        
        if char1 in map1to2:
            if map1to2[char1] != char2:
                return False
        else:
            map1to2[char1] = char2
        
        if char2 in map2to1:
            if map2to1[char2] != char1:
                return False
        else:
            map2to1[char2] = char1
    
    return True

# Test examples
test_cases = [("aab", "xxy"), ("aab", "xyz"), ("paper", "title"), ("foo", "bar")]

for s1, s2 in test_cases:
    result = are_isomorphic(s1, s2)
    print(f"'{s1}' and '{s2}' are isomorphic: {result}")
'aab' and 'xxy' are isomorphic: True
'aab' and 'xyz' are isomorphic: False
'paper' and 'title' are isomorphic: True
'foo' and 'bar' are isomorphic: False

How It Works

The algorithm works by:

  1. Length Check: First verifying both strings have equal length
  2. Character Mapping: Creating a bidirectional mapping between characters
  3. Validation: Ensuring each character maps consistently throughout the strings
  4. Conflict Detection: Returning False if any mapping conflict is found

Comparison

Method Time Complexity Space Complexity Readability
Array-based O(n) O(1) - fixed size arrays Lower
Dictionary-based O(n) O(k) - k unique characters Higher

Conclusion

Both methods effectively check string isomorphism with O(n) time complexity. The dictionary approach is more readable and Pythonic, while the array method uses constant space for ASCII characters.

Updated on: 2026-03-26T02:52:55+05:30

474 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements