Isomorphic strings

Can every character of one string be swapped for a fixed character in another, with the swap working both ways?

Time O(n)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Isomorphic means every character in s can be swapped for a fixed character in t, and the swap has to work in both directions. One dictionary remembers s -> t; a second remembers t -> s. If either direction would ever need to send the same character to two different partners, the strings are not isomorphic.

Code

public static bool IsIsomorphic(string s, string t) {
    if (s.Length != t.Length) return false;
    var mapST = new Dictionary<char, char>();
    var mapTS = new Dictionary<char, char>();
    for (int i = 0; i < s.Length; i++) {
        char a = s[i], b = t[i];
        if (mapST.TryGetValue(a, out char mb) && mb != b) return false;
        if (mapTS.TryGetValue(b, out char ma) && ma != a) return false;
        mapST[a] = b; mapTS[b] = a;
    }
    return true;
}
static boolean isIsomorphic(String s, String t) {
    if (s.length() != t.length()) return false;
    Map<Character, Character> mapST = new HashMap<>();
    Map<Character, Character> mapTS = new HashMap<>();
    for (int i = 0; i < s.length(); i++) {
        char a = s.charAt(i), b = t.charAt(i);
        if (mapST.containsKey(a) && mapST.get(a) != b) return false;
        if (mapTS.containsKey(b) && mapTS.get(b) != a) return false;
        mapST.put(a, b); mapTS.put(b, a);
    }
    return true;
}
bool isIsomorphic(const string& s, const string& t) {
    if (s.size() != t.size()) return false;
    unordered_map<char, char> mapST;
    unordered_map<char, char> mapTS;
    for (size_t i = 0; i < s.size(); i++) {
        char a = s[i], b = t[i];
        if (mapST.count(a) && mapST[a] != b) return false;
        if (mapTS.count(b) && mapTS[b] != a) return false;
        mapST[a] = b; mapTS[b] = a;
    }
    return true;
}
def is_isomorphic(s: str, t: str) -> bool:
    if len(s) != len(t): return False
    map_st = {}
    map_ts = {}
    for a, b in zip(s, t):
        if a in map_st and map_st[a] != b: return False
        if b in map_ts and map_ts[b] != a: return False
        map_st[a] = b; map_ts[b] = a
    return True

Tips

In the .NET library

This is the same "remember what has been paired so far" idea as Two Sum, just applied twice, once per direction, so a many-to-one mapping in either direction gets caught.