Isomorphic Strings – Solution & Complexity
Solution Walkthrough
Step 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.
- Each character of
Step 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.
- A common first attempt maps only
Step 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.
Step 4: Two-map solution
forwardmaps characters ofstot;backwardmapstback tos.- Reject as soon as either map disagrees with the current pair.
Step 5: Dry run
Trace
s = "paper",t = "title".i a b forward backward ok? 0 p t p->tt->pyes 1 a i a->ii->ayes 2 p t consistent consistent yes 3 e l e->ll->eyes 4 r e r->ee->ryes No conflict, so the answer is
true.Step 6: Final solution and complexity
Two hashmaps enforce a bijection in
O(n)time andO(1)extra space for a bounded alphabet.