How to check if two strings are isomorphic in Python

2 Answers

0 votes
# Two strings are isomorphic if characters in one can be replaced to get the other, 
# while preserving the order.

def are_isomorphic(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False

    map_st = {}
    map_ts = {}

    for c1, c2 in zip(s, t):
        # Check mapping from s → t
        if c1 in map_st:
            if map_st[c1] != c2:
                return False
        else:
            map_st[c1] = c2

        # Check mapping from t → s
        if c2 in map_ts:
            if map_ts[c2] != c1:
                return False
        else:
            map_ts[c2] = c1

    return True


print(are_isomorphic("egg", "add"))     
print(are_isomorphic("foo", "bar"))     
print(are_isomorphic("paper", "title")) 



'''
run:

True
False
True

'''

 



answered Dec 19, 2025 by avibootz
edited Dec 19, 2025 by avibootz
0 votes
def are_isomorphic(s: str, t: str) -> bool:
    return [s.index(c) for c in s] == [t.index(c) for c in t]

print(are_isomorphic("egg", "add"))     
print(are_isomorphic("foo", "bar"))     
print(are_isomorphic("paper", "title")) 



'''
run:

True
False
True

'''

 



answered Dec 19, 2025 by avibootz
...