Isomorphic Strings
Master this topic with zero to advance depth.
Isomorphic Strings
Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
Visual Representation
s = "egg", t = "add"
e -> a
g -> d
Result: "add" (True)
s = "foo", t = "bar"
f -> b
o -> a
o -> r (Conflict! 'o' already mapped to 'a')Examples
Level I: Two HashMaps (Bidirectional)
Intuition
A character in s must map to exactly one character in t, and vice versa. We use two maps to ensure this 1-to-1 relationship.
Detailed Dry Run
s="ab", t="aa" m1: {a: a}, m2: {a: a} m1: {b: a}, m2 already has {a: a}! Conflict.
Level II: Last Seen Index (Space Optimized)
Intuition
Characters are isomorphic if they appear at the same relative indices throughout the string. We track the 'last seen' index for each character.
Detailed Dry Run
s="egg", t="add" e(0), a(0) -> Match g(1), d(1) -> Match g(2), d(2) -> Match
Level III: Optimal Solution (Canonical Form)
Intuition
Convert both strings to a 'canonical' or 'normal' form where each character is replaced by the index of its first appearance. If both strings produce the same normalized form, they are isomorphic.
Detailed Dry Run
s = "paper" -> First seen indices: p:0, a:1, e:3, r:4. Normalized: [0, 1, 0, 3, 4] t = "title" -> First seen indices: t:0, i:1, l:3, e:4. Normalized: [0, 1, 0, 3, 4] Match!
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.