Isomorphic String
EasyThe mapping must work both ways
Problem
Return whether two strings are isomorphic: characters of one can be consistently mapped to characters of the other (one-to-one).
Each letter must map to exactly one partner both ways — track two mappings.
The idea
Walk both strings in step, recording the mapping from each character of one to the corresponding character of the other. Keeping two maps is essential: a single map would allow two different characters to map onto the same target, which is not isomorphic.
The trick
- Two maps, one in each direction — one map alone accepts 'badc' -> 'baba'.
- Different lengths are an immediate no.
- O(n) time, O(alphabet) space.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — egg, add Values: 0.
1map s->t and t->s2for i: if mappings conflict: return false; else set them3return trueInput
- array
- [0]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- s = "egg", t = "add"
- Output:
- true
- Explanation:
- e->a, g->d is a clean one-to-one mapping.
Example 2
- Input:
- s = "foo", t = "bar"
- Output:
- false
- Explanation:
- o would need to map to two letters → false.
Example 3
- Input:
- s = "paper", t = "title"
- Output:
- true
- Explanation:
- Every letter maps consistently.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.