To check whether two strings are isomorphic, we need to understand whether we can map each character in the first string to a unique character in the second string — and do so consistently throughout the entire string.
Imagine we are translating every character from s
to t
. If 'a'
in s
maps to 'x'
in t
, then every time we see 'a' in s
, it must be translated to 'x'
. If we see 'a' later mapping to a different character (like 'y'), the strings are not isomorphic.
We also need to make sure that no two different characters in s
map to the same character in t
. For example, if both 'a'
and 'b'
map to 'x'
, that breaks the one-to-one requirement.
To implement this, we can use two hash maps (or dictionaries):
s_to_t
: Maps characters from s
to t
.
t_to_s
: Maps characters from t
to s
.
As we iterate through the characters of both strings, we:
- Check if the current character from
s
has already been mapped to something in t
. If it has, and the mapping doesn't match the current character in t
, we return false
.
- Similarly, we check that the character in
t
hasn't already been assigned to a different character from s
.
If we finish the loop and all mappings are valid, we return true
.
Special Cases to Consider:
- Empty strings: Two empty strings are trivially isomorphic — no characters means no conflicts.
- Different lengths: If the strings are of unequal length, they can never be isomorphic, because we can't map characters one-to-one.
- Repeated characters: It's okay if a character appears multiple times — as long as it always maps to the same character in the other string, and no conflicts arise.
This explanation focuses on helping beginners reason through character mapping with clarity before worrying about code or efficiency.