Isomorphic Strings – Solution & Complexity
Solution Walkthrough
1. Define isomorphism precisely
- Each character of
smust always translate to the same character oft. - The translation must be reversible: no two
scharacters share attarget. - That is a bijection between the characters that appear.
2. Track a single mapping (why it fails)
- A common first attempt maps only
s -> t. - That misses collisions like
"ab" -> "aa", where twoscharacters map to the sametcharacter. - We therefore need to guard both directions.
3. Maintain forward and backward maps
- Walk both strings in lockstep.
- For each pair
(a, b), verify any existinga -> bandb -> amappings still agree. - If a conflict appears, the strings are not isomorphic.
4. Two-map solution
forwardmaps characters ofstot;backwardmapstback tos.- Reject as soon as either map disagrees with the current pair.
5. Dry run
Trace s = "paper", t = "title".
| i | a | b | forward | backward | ok? |
|---|---|---|---|---|---|
| 0 | p | t | p->t | t->p | yes |
| 1 | a | i | a->i | i->a | yes |
| 2 | p | t | consistent | consistent | yes |
| 3 | e | l | e->l | l->e | yes |
| 4 | r | e | r->e | e->r | yes |
No conflict, so the answer is true.
6. Final solution and complexity
Two hashmaps enforce a bijection in O(n) time and O(1) extra space for a bounded alphabet.