← Back to Leo Academy Masterclass

Problem #205: Isomorphic Strings

Easy Hashmap

Intuition & Strategy Breakdown

Maintain two character mapping hash maps (s -> t and t -> s). Ensure each character maps bijectively to exactly one target character.

Python Solution

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        mapST, mapTS = {}, {}
        for c1, c2 in zip(s, t):
            if (c1 in mapST and mapST[c1] != c2) or (c2 in mapTS and mapTS[c2] != c1):
                return False
            mapST[c1] = c2
            mapTS[c2] = c1
        return True

Java Solution

class Solution {
    public boolean isIsomorphic(String s, String t) {
        int[] m1 = new int[256], m2 = new int[256];
        for (int i = 0; i < s.length(); i++) {
            if (m1[s.charAt(i)] != m2[t.charAt(i)]) return false;
            m1[s.charAt(i)] = i + 1;
            m2[t.charAt(i)] = i + 1;
        }
        return true;
    }
}
Watch Interactive Video on Leo Academy Main App