You are given two strings s and t, determine if they are isomorphic.
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.
Example 1:
Input: s = "egg", t = "add"
Output: trueExplanation: The strings s and t can be made identical by:
Example 2:
Input: s = "foo", t = "bar"
Output: falseExplanation: The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'.
Example 3:
Input: s = "paper", t = "title"
Output: trueConstraints:
0 <= s.length == t.length <= 50,000s and t consist of any valid ascii character.Before attempting this problem, you should be comfortable with:
Two strings are isomorphic if there's a one-to-one mapping between their characters. We need to ensure that each character in s maps to exactly one character in t, and vice versa. A single pass checking only s -> t mapping isn't enough because two different characters in s could map to the same character in t. By running the check twice (once for (s, t) and once for (t, s)), we guarantee the mapping is bijective.
(s, t) and once with (t, s).true only if both checks pass.class Solution:
def helper(self, s: str, t: str) -> bool:
mp = {}
for i in range(len(s)):
if (s[i] in mp) and (mp[s[i]] != t[i]):
return False
mp[s[i]] = t[i]
return True
def isIsomorphic(self, s: str, t: str) -> bool:
return self.helper(s, t) and self.helper(t, s)Where is the length of the input string and is the number of unique characters in the strings.
We can verify both mapping directions simultaneously in a single pass. By maintaining two hash maps, one for s -> t and one for t -> s, we check at each position that neither mapping is violated. If a character in s was previously mapped to a different character in t, or if a character in t was previously mapped to a different character in s, the strings aren't isomorphic.
mapST for s -> t and mapTS for t -> s.s[i] already maps to something other than t[i], return false.t[i] already maps to something other than s[i], return false.true.Where is the length of the input string and is the number of unique characters in the strings.
Checking only that each character in s maps to a unique character in t is insufficient. You must also verify the reverse: that each character in t maps to a unique character in s. For example, s = "ab" and t = "aa" would pass a one-way check but fails the bidirectional requirement since both 'a' and 'b' map to 'a'.
The two strings may contain completely different character sets. Do not assume that a character appearing in s must also appear in t, or vice versa. The mapping must be established dynamically as you iterate through both strings.