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
Check if two strings s and t are isomorphic, meaning characters in s can be replaced to get t while preserving the character mapping. Each character must map to exactly one other character, and no two characters can map to the same character. Use two hash maps tracking s-to-t and t-to-s mappings.
Both direction maps ensure the mapping is a bijection. When a new character pair is encountered, both maps are updated. Any conflict with an existing mapping returns false.
Time complexity is O(n), space complexity is O(k).
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.
