Isomorphic Strings Problem
Description
LeetCode Problem 205.
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: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "paper", t = "title"
Output: true
Constraints:
- 1 <= s.length <= 5 * 10^4
- t.length == s.length
- s and t consist of any valid ascii character.
Solution
Approach: Two Hash Maps
Walk through both strings together. At position i, character s[i] must be replaced by t[i]. The replacement has to be consistent in both directions:
- the same character of
smust always become the same character oft, and - no two different characters of
smay become the same character oft.
So keep two maps: sToT (which character of t replaces each character of s) and tToS (which character of s each character of t came from). For each pair a = s[i], b = t[i]:
- If
ais already insToTbut maps to something other thanb, returnfalse. - If
bis already intToSbut maps to something other thana, returnfalse. - Otherwise record
a -> bandb -> a.
If the loop finishes, every pair was consistent, so the strings are isomorphic.
The detail people miss is the second map. With only sToT, s = "badc" and t = "baba" would pass: b -> b, a -> a, d -> b, c -> a never contradicts itself, yet b and d both become b, which is not allowed.
Complexity: O(n) time, where n is the length of s. O(k) space, where k is the number of distinct characters (at most 128 for ASCII).
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
s_to_t = {} # character of s -> the character of t that replaces it
t_to_s = {} # character of t -> the character of s it replaces
for a, b in zip(s, t):
if a in s_to_t and s_to_t[a] != b:
return False # a is already replaced by a different character
if b in t_to_s and t_to_s[b] != a:
return False # another character of s already maps to b
s_to_t[a] = b
t_to_s[b] = a
return True
Now write it from memory
Close the write-up and solve it yourself against the tests.