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#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

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;
}

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.