Understanding the Problem
We are given two strings, s
and t
, and we need to determine whether they are isomorphic.
Two strings are isomorphic if characters in one string can be replaced to get the second string — with a consistent, one-to-one mapping.
This means:
- Every character in
s
maps to exactly one character in t
.
- No two characters from
s
map to the same character in t
.
Think of this as a character-translation problem: we’re translating each character in s
to a character in t
. The translation must be consistent and unique.
Step-by-Step Solution with Example
Step 1: Take a simple example
Let’s consider the example: s = "egg"
and t = "add"
We’ll walk through each character pair and see how the mappings work.
Step 2: Use two hash maps
We use two maps (dictionaries):
s_to_t
: Maps characters from s
to t
t_to_s
: Maps characters from t
to s
Step 3: Iterate through the strings
We loop through each character pair:
i = 0 → s[0] = 'e', t[0] = 'a'
→ 'e' is not in s_to_t → map 'e' → 'a'
→ 'a' is not in t_to_s → map 'a' → 'e'
i = 1 → s[1] = 'g', t[1] = 'd'
→ 'g' is not in s_to_t → map 'g' → 'd'
→ 'd' is not in t_to_s → map 'd' → 'g'
i = 2 → s[2] = 'g', t[2] = 'd'
→ 'g' is already mapped to 'd' → OK
→ 'd' is already mapped to 'g' → OK
All characters follow consistent one-to-one mapping. So, the strings are isomorphic.
Step 4: Check for mismatches
Let’s consider another example: s = "foo"
, t = "bar"
i = 0 → 'f' → 'b'
i = 1 → 'o' → 'a'
i = 2 → 'o' → 'r' → ❌ mismatch! 'o' was already mapped to 'a'
So we return false
.
Edge Cases
- Empty Strings: If both
s
and t
are empty, they are trivially isomorphic — nothing to map, no conflict.
- Different Lengths: If
s.length !== t.length
, they can’t be isomorphic. Each character must have a match.
- Repeated Characters: Repetition is fine as long as the mapping stays consistent. For example:
s = "paper"
, t = "title"
→ Valid isomorphic pair.
Finally
To solve this problem:
- Understand the core rule — one-to-one and consistent character mapping.
- Use two dictionaries to track both directions of mapping.
- Validate that no character breaks the mapping rule during iteration.
This approach is simple, beginner-friendly, and ensures you check all logical mapping conditions.
Comments
Loading comments...