185. Isomorphic Strings
Your function receives two strings s and t of the same length and returns true if they are isomorphic, false otherwise.
Two strings are isomorphic when there is a consistent character substitution turning s into t:
- every occurrence of a character in
smust be replaced by the same character int, and - two different characters in
smay never map to the same character int.
A character is allowed to map to itself. For instance egg and add are isomorphic (e→a, g→d), but badc and baba are not — d and b would both have to become a.
Example 1:
Input: s = "egg", t = "add"
Output: true
Explanation: Substituting e→a and g→d turns egg into add, and no two source characters share a target.
Example 2:
Input: s = "foo", t = "bar"
Output: false
Explanation: The two o's would need to become both a and r — one character cannot map to two different targets.
Example 3:
Input: s = "paper", t = "title"
Output: true
Explanation: p→t, a→i, e→l, r→e is a consistent one-to-one substitution.
Constraints:
- 1 ≤ s.length ≤ 5 * 10⁴
- t.length == s.length
- s and t consist of printable ASCII characters with no spaces
Hints:
Walk both strings in lockstep and record what each character of s has been translated to so far. When you meet a character you've translated before, what must be true for the strings to still be isomorphic?
One map isn't enough: `ab` → `aa` passes a forward-only check (a→a, b→a) but breaks the one-to-one rule. Either keep a second map from t back to s, or compare 'fingerprints': replace each character by the index of its first occurrence in its own string and check the two encoded sequences match.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = "egg", t = "add"
Expected output: true