sagelearnai

Isomorphic Strings

Difficulty: Easy · Pattern: Hashing · LeetCode #205

Strings s and t are isomorphic if the characters of s can be replaced consistently to get t: every occurrence of a character maps to the same character, and no two characters map to the same one.

Examples

text
"egg", "add"      →  true
"foo", "bar"      →  false
"paper", "title"  →  true
"badc", "baba"    →  false

Hints

  1. A single map s→t isn't enough: "badc" → "baba" maps both b and d to b.
  2. Track both directions.

Approach

Walk both strings together, keeping s→t and t→s maps. If a character already has a mapping that disagrees with the current pair in either direction, return false. Two maps enforce a bijection. O(n).

Complexity

Time: O(n). Space: O(alphabet).

Python solution
def isIsomorphic(s, t):
    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
JavaScript solution
function isIsomorphic(s, t) {
  const st = new Map(), ts = new Map();
  for (let i = 0; i < s.length; i++) {
    const a = s[i], b = t[i];
    if ((st.has(a) && st.get(a) !== b) || (ts.has(b) && ts.get(b) !== a)) return false;
    st.set(a, b); ts.set(b, a);
  }
  return true;
}