Problem Statement

Isomorphic Strings

You get two strings, s and t. The question: can you turn s into t by swapping out letters in a clean, consistent way? "Isomorphic" just means same shape. Two strings have the same shape if every letter in s always becomes the exact same letter in t, and no two different letters in s ever turn into the same letter in t. Think of it like a secret code where each letter has one and only one partner. To check this, we use two hash maps. A hash map (also called a dictionary) is like a lookup table: you give it a key, it gives you back the value you stored under that key. We use one map for s to t (what each s letter turns into) and one map for t to s (what each t letter came from). The two maps together make sure the code works perfectly in both directions.

easyHash TableArrays & HashingTime: O(n) · Space: O(1)

Signals to notice

check if two strings have same character mapping patternbidirectional mappingisomorphic check

Brute force first

Try all possible character mappings — O(26!). Impractical.

The key insight

Two hash maps: s→t and t→s. For each position, check that both mappings are consistent. If s[i] maps to a different t character or vice versa, not isomorphic. O(n).

Trace it on s="paper", t="title"

len(s)==len(t)==5 -> ok. s_to_t={}, t_to_s={}
i=0 (p,t): neither mapped -> set s_to_t={p:t}, t_to_s={t:p}
i=1 (a,i): neither mapped -> set s_to_t={p:t,a:i}, t_to_s={t:p,i:a}
i=2 (p,t): s_to_t[p]==t ok, t_to_s[t]==p ok -> consistent, re-set (no change)
i=3 (e,l): neither mapped -> set s_to_t={...,e:l}, t_to_s={...,l:e}
i=4 (r,e): neither mapped -> set s_to_t={...,r:e}, t_to_s={...,e:r}
loop ends, all positions consistent -> return True

What must stay true

The mapping must be bidirectional — s[i]→t[i] AND t[i]→s[i] must both be consistent. A one-way check misses cases like 'ab'→'aa'.

Shape of the loop

if len(s) != len(t): return false
s_to_t, t_to_s = {}, {}
for (cs, ct) in zip(s, t):
    if s_to_t.get(cs, ct) != ct or t_to_s.get(ct, cs) != cs: return false
    s_to_t[cs] = ct; t_to_s[ct] = cs
return true

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Only checking one direction — 'ab' maps to 'aa' is consistent s→t but not t→s (both a and b map to a, but a maps to both a and b).

Arrays & Hashing Pattern