Isomorphic Strings
LeetCode 205 · View on LeetCode
Two strings are isomorphic if each character in s maps to exactly one character in t, and vice versa. Same position, consistent mapping both directions.
Why frequency counting alone fails: s = "bbbaaaba", t = "aaabbbba" have the same frequency distribution, but b maps to both a and b at different positions — not isomorphic.
Correct approach: Two dicts ensuring a bijection (one-to-one both ways).
def is_isomorphic(s: str, t: str) -> bool:
s_to_t = {}
t_to_s = {}
for a, b in zip(s, t):
if a in s_to_t and s_to_t[a] != b:
return False
if b in t_to_s and t_to_s[b] != a:
return False
s_to_t[a] = b
t_to_s[b] = a
return True
if __name__ == '__main__':
print(is_isomorphic("egg", "add")) # True (e→a, g→d)
print(is_isomorphic("foo", "bar")) # False (o→a then o→r)
print(is_isomorphic("paper", "title")) # True (p→t, a→i, e→l, r→e)
print(is_isomorphic("ab", "aa")) # False (a→a, b→a — two chars map to same)