Isomorphic Strings

Decide whether one string can be turned into another by swapping each character for one fixed partner.

Given two strings s and t, decide whether they are isomorphic. They are isomorphic when the characters of s can be replaced to get t. Every copy of a character must be replaced by the same character, and no two different characters may be replaced by the same one. A character may be replaced by itself.

Example 1
Input: s = "egg", t = "add"
Output: true
Explanation: e → a, g → d.
Example 2
Input: s = "foo", t = "bar"
Output: false
Explanation: o would have to become both a and r.
Example 3
Input: s = "paper", t = "title"
Output: true
Solution

The Idea

You may have seen a simple secret code where every letter of a message is swapped for another letter: every a becomes x, every b becomes q, and so on. To read the message, you swap each letter back. Two strings are isomorphic when t is s written in such a code.

Line up Example 3 position by position: p over t, a over i, p over t again, e over l, and r over e. Both copies of p sit over t, so the pairs never disagree. The code is p → t, a → i, e → l and r → e, and swapping each letter back gives "paper" again.

Example 2 breaks the code in an obvious way. In "foo" over "bar", the first o sits over a and the second o over r, so one letter would have to become two. Is that the only way to break it?

Try s = "badc" and t = "baba". No letter of s sits over two different letters: b over b, a over a, d over b and c over a. Yet both b and d would become b, so a b in "baba" could be read back as either one. Look at the picture below.

Left: paper to title pairs p with t, a with i, e with l and r with e, one arrow out of and into each letter. Right: badc to baba pairs b with b, a with a, d with b and c with a, so two arrows end at b and two at a.

In the panel labelled "paper → title", each letter of s has one arrow out and each letter of t has one arrow in. In the panel labelled "badc → baba", every letter of s still has one arrow out, but two arrows end at b and two at a.

So the pairing must hold in both directions. Each character of s always meets the same character of t, and each character of t always meets the same character of s. Put another way, the two strings repeat their letters in the same pattern: "paper" repeats a letter at positions 0 and 2, and so does "title".

Solution Approach

Turning that idea into code means settling three things: checking the pairing both ways with two maps, replacing both maps with one check of where each character was last seen, and storing those positions in plain arrays.

Checking both directions with two maps

How do we check the pairing while reading the strings? Walk both strings together and keep two maps: one from each character of s to its partner in t, and one the other way. At each position, if either character already has a partner and it is a different character, the answer is false.

Both maps are needed. A map from s to t alone accepts "badc" and "baba", because d is new and simply gets b. Only the map from t to s notices that the b in t is already paired with the b in s.

Comparing last positions

Can one check do the work of both maps? Look at where each character was last seen. As long as the pairing has held, a character of s and its partner in t have always appeared at the same positions, so they were last seen at the same position too.

Take "badc" and "baba" again. At index 2, s has d, never seen before, while t has b, last seen at index 0. The two last positions differ, so the answer is false. In general, the first time a character meets a new partner, one of the two characters has been seen at a position where the other has not, and the check fails right there.

Storing the positions in arrays

Where do the last positions live? A Java char is a number, so it can index an array directly. Two arrays of 256 ints, one per string, cover every ASCII character (the 128 basic letters, digits and symbols, codes 0 to 127) and the rest of the codes up to 255, with no hashing.

Each slot stores the position plus one, so that 0 can mean "not seen yet". Storing the plain position would make index 0 look unseen. Then "ab" and "aa" would pass: at index 1, b was never seen and a was last seen at index 0, and both read as 0.

The arrays assume no character code above 255. The euro sign € has code 8364, and passing a string that contains it throws an ArrayIndexOutOfBoundsException. For text like that, use arrays of 65,536 ints, one per possible char, or the two maps.

Java Solution

The method isIsomorphic works in these steps:

  1. First, compare the lengths. Strings of different lengths cannot pair up position by position, so return false. This also keeps t.charAt(i) in range later.
  2. Create two arrays of 256 ints, lastS for s and lastT for t. They start as all zeros, meaning no character has been seen.
  3. Walk both strings with one loop over the index i, reading a = s.charAt(i) and b = t.charAt(i).
  4. If lastS[a] differs from lastT[b], the two characters were last seen at different places, so return false.
  5. Otherwise store i + 1 in both lastS[a] and lastT[b], and go on to the next index.
  6. If the loop gets through every index, every pair agreed, so return true.

The main method runs the three examples, then "badc" and "baba", then "ab" and "aa", strings of different lengths, and two empty strings.

Java
public class IsomorphicStrings {

    public static boolean isIsomorphic(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        // last position (+1) where each character was seen; 0 means "not seen yet"
        int[] lastS = new int[256];
        int[] lastT = new int[256];
        for (int i = 0; i < s.length(); i++) {
            char a = s.charAt(i);
            char b = t.charAt(i);
            if (lastS[a] != lastT[b]) {
                return false;                 // a and b were last seen at different places
            }
            lastS[a] = i + 1;
            lastT[b] = i + 1;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isIsomorphic("egg", "add"));
        System.out.println(isIsomorphic("foo", "bar"));
        System.out.println(isIsomorphic("paper", "title"));
        System.out.println(isIsomorphic("badc", "baba"));
        System.out.println(isIsomorphic("ab", "aa"));
        System.out.println(isIsomorphic("ab", "abc"));
        System.out.println(isIsomorphic("", ""));
    }
}

Running it prints:

Output
true
false
true
false
false
false
true

For "egg" and "add" the method prints true, for "foo" and "bar" false, and for "paper" and "title" true, as Examples 1 to 3 expect. The fourth value, false, is "badc" and "baba", the pair that a single map from s to t lets through.

The fifth value is "ab" and "aa", and it is false because the arrays store the position plus one. With the plain position stored instead, this line prints true. The sixth value comes from the length check, since "abc" has one character more than "ab". The last value is true: two empty strings have no positions, so nothing can disagree.

The original implementation, IsomorphicStrings.java, is on GitHub.

Complexity

The method makes one pass over the two strings and keeps two arrays whose size never changes.

  • Time: O(n) for two strings of n characters, because the loop visits each position at most once, with two array reads, one comparison and two writes per position, and it stops early at the first disagreement.
  • Space: O(1). The two arrays hold 256 ints each, a size set by the character codes rather than by the length of the strings.

The same two-way check, applied to letters and words, is Word Pattern.