Isomorphic Strings
Decide whether one string can be turned into another by swapping each character for one fixed partner.
Given two strings stst
Example 1
Output: true
Explanation: e → a, g → d.
Example 2
Output: false
Explanation: o would have to become both a and r.
Example 3
Output: true
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 ts
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"t = "baba"s
In the panel labelled "paper → title", each letter of sts
So the pairing must hold in both directions. Each character of stts
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 st
Both maps are needed. A map from sttsts
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 st
Take "badc" and "baba" again. At index 2, st
Storing the positions in arrays
Where do the last positions live? A Java char
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 ArrayIndexOutOfBoundsExceptionchar
Java Solution
The method isIsomorphic
- First, compare the lengths. Strings of different lengths cannot pair up position by position, so return
. This also keepsfalse in range later.t.charAt(i) - Create two arrays of 256 ints,
forlastS ands forlastT . They start as all zeros, meaning no character has been seen.t - Walk both strings with one loop over the index
, readingi anda = s.charAt(i) .b = t.charAt(i) - If
differs fromlastS[a] , the two characters were last seen at different places, so returnlastT[b] .false - Otherwise store
in bothi + 1 andlastS[a] , and go on to the next index.lastT[b] - If the loop gets through every index, every pair agreed, so return
.true
The main
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:
true
false
true
false
false
false
true
For "egg" and "add" the method prints truefalsetruefalsest
The fifth value is "ab" and "aa", and it is falsetruetrue
The original implementation,
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