Two strings are isomorphic when the character pattern in one string can be matched to the character pattern in the other string with a consistent one-to-one mapping.
That means if a character in the first string appears again later, it must map to the same character again in the second string. It also means two different characters from the first string are not allowed to collapse into the same character in the second string.
For example, "egg" and "add" are isomorphic because e -> a and g -> d stay consistent across the whole string. But "foo" and "bar" are not isomorphic because the repeated o would need to map inconsistently.
So the task is to check whether one stable one-to-one character mapping can explain every position in both strings.
Example Input & Output
e->a and g->d is consistent.
o cannot map to both a and r.
A consistent one-to-one mapping exists.
Algorithm Flow

Solution Approach
The cleanest hash table solution is to keep two maps: one from characters in s to characters in t, and one from characters in t back to characters in s.
Using two maps matters because consistency has to work in both directions. If we only store s -> t, we could miss a bad case where two different characters in s both point to the same character in t.
We scan the strings position by position. At index i, let the characters be a = s[i] and b = t[i]. There are two checks.
If a was seen before, it must map to exactly b. If not, the strings are not isomorphic. If b was seen before in the reverse map, it must map back to exactly a. If not, the strings are also not isomorphic.
If both checks pass, we store the pair in both maps and continue:
If we finish the loop without any contradiction, then every repeated letter followed the same pattern and no two letters tried to share the same partner. That means the strings are isomorphic. This solution runs in O(n) time with O(k) extra space.
Best Answers
import java.util.*;
class Solution {
public boolean isomorphic_strings(String s, String t) {
if (s.length() != t.length()) return false;
Map<Character, Character> st = new HashMap<>();
Map<Character, Character> ts = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i), b = t.charAt(i);
if (st.containsKey(a) && st.get(a) != b) return false;
if (ts.containsKey(b) && ts.get(b) != a) return false;
st.put(a, b);
ts.put(b, a);
}
return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
