Isomorphic Strings

Pattern: Strings basics and frequency

easy

Each character of s must always become the same character of t, and no two characters of s may become the same one. Keep a map in each direction and check every pair against both.

The problem

Two strings s and t of the same length are isomorphic if you can replace characters in s to get t, where every copy of a character is replaced by the same character, and no two different characters are replaced by the same one. A character may map to itself. For example, "egg" and "add" are isomorphic, "foo" and "bar" are not, and "paper" and "title" are.

The function name isIsomorphic matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • What goes wrong in "foo" and "bar"?
  • What goes wrong in "badc" and "baba"?
  • Why does one map from s to t not catch both problems?

Hints

    Brute force, and why it fails

    For every pair of positions i, j, check that s[i] == s[j] exactly when t[i] == t[j]: O(n²). Two maps check the same thing in O(n).

    The key insight

    "Isomorphic" means the mapping is one-to-one. One-to-one needs a check in both directions, so two maps, each kept consistent, are exactly the right tool.

    Dry run

    p-t0 
    a-i1 
    p-t2 
    e-l3 
    r-e4 

    s = paper and t = title. Pair the characters position by position.

    Step 1 of 4

    The plan

    sToT = empty map, tToS = empty map
    for i from 0 to n - 1:
        a = s[i], b = t[i]
        if a not in sToT and b not in tToS: sToT[a] = b; tToS[b] = a
        else if sToT[a] != b or tToS[b] != a: return false
    return true
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass. The maps hold at most one entry per distinct character, which is bounded by the alphabet size.

    Edge cases

    • One character each: always true.
    • "ab" and "aa": false, because a and b would both become a.
    • A character mapping to itself is fine.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isIsomorphic(String s, String t) {
            int[] sToT = new int[256], tToS = new int[256];        // 0 means "not mapped yet"
            for (int i = 0; i < s.length(); i++) {
                char a = s.charAt(i), b = t.charAt(i);
                if (sToT[a] == 0 && tToS[b] == 0) { sToT[a] = b; tToS[b] = a; }   // a new pair
                else if (sToT[a] != b || tToS[b] != a) return false;               // clashes with an old pair
            }
            return true;
        }
    }

    C++

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            int sToT[256] = {0}, tToS[256] = {0};                   // 0 means "not mapped yet"
            for (size_t i = 0; i < s.size(); i++) {
                unsigned char a = s[i], b = t[i];
                if (sToT[a] == 0 && tToS[b] == 0) { sToT[a] = b; tToS[b] = a; }   // a new pair
                else if (sToT[a] != b || tToS[b] != a) return false;               // clashes with an old pair
            }
            return true;
        }
    };

    Python

    class Solution:
        def isIsomorphic(self, s: str, t: str) -> bool:
            s_to_t, t_to_s = {}, {}
            for a, b in zip(s, t):
                if a not in s_to_t and b not in t_to_s:
                    s_to_t[a], t_to_s[b] = b, a     # a new pair
                elif s_to_t.get(a) != b or t_to_s.get(b) != a:
                    return False                    # clashes with an old pair
            return True

    Common mistakes

    • Using one map only, which accepts "badc" and "baba".
    • Comparing letter counts only. "abab" and "aabb" have the same counts but are not isomorphic.
    • Forgetting that 0 in a Java or C++ array means "not mapped yet", so use a value no character can have.

    Similar problems