SDE & MLE Prep

205. Isomorphic Strings

Problem

Two strings s and t of equal length are isomorphic if the characters of s can be replaced to get t, where each character maps to exactly one character, consistently, and no two characters map to the same one. Decide whether s and t are isomorphic.

Example: s = "egg", t = "add" → true; s = "foo", t = "bar" → false

Need a bijection: map s→t and t→s. A conflict in either direction → false.

Complexity: O(n).

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        st, ts = {}, {}
        for a, b in zip(s, t):
            if st.setdefault(a, b) != b or ts.setdefault(b, a) != a:
                return False
        return True